1. TextView 基础属性详解
id:给 TextView 设置一个组件id
layout_width:组件的宽度
layout_height:组件的高度
text:设置显示的文本内容
textColor:设置字体颜色
textStyle:设置字体风格,三个可选值,nomal(无效果),bold(加粗),italic(斜体)
textSize:字体大小,单位一般是用 sp
background:控件的背景颜色,可以更解为填充整个控件的颜色,可以是图片
gravity:设置控件中内容的对齐方向,TextView 中是文字,imageView中是图片等等示例代码:
<TextView android:id="@+id/one_tv" android:layout_width="200dp" android:layout_height="200dp" android:text="HelloAndroid" android:textColor="#FF0000FF" android:textStyle="normal" android:textSize="30sp" android:background="@color/white" android:gravity="center" />
(1)上面通过对控件 id 的配置,后续需获取该控件的时候,只需通过 findViewById ( R.id.xxx ) 即可获取到该控件。如下:
TextView one_tv = findViewById(R.id.one_tv);
(2)上面的写法是直接对控件的属性赋值,但是正规开发是不会这么写的,一般会将需要显示的内容或值 抽取到 res/values 目录下的配置文件来配置,如 colors.xml 或者是 strings.xml 。在使用的时候,通过名字指向对应的值。这样的做法有利于解耦以及后续代码的适配。
如可以将上文的 “HelloAndroid” 抽取到 strings.xml 文件中,并给它分配一个名字,叫“tv_one”。如下:
<resources> <string name="app_name">My Application</string> <string name="tv_one">HelloAndroid</string> </resources>
使用的时候,设置控件text属性的值为 "@string/tv_one" ,即等于将控件的内容设置文本 “HelloAndroid”。
如下所示:<TextView android:text="@string/tv_one"/>
后面若需改动显示的文本,控件属性值设置的地方则无需变动,只需改动 strings.xml 对应名字的值即可,达到“一处修改,多处同步”的目的。
(3)textColor 属性也是如此,上文写了 "#FF0000FF",该颜色码一共8位。其中#号后面的第 1、2 位表示透明度;第3、4位表示红色;第5、6位表示绿色;第7、8位表示蓝色。同样,这里可以使用 res/values/colors.xml 预先设置好的颜色,如 "@color/black"等。 可将 textColor 的值修改成如下所示:<TextView android:textColor="@color/black"/>
修改后,activity_main.xml 完整的代码如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/one_tv" android:layout_width="200dp" android:layout_height="200dp" android:text="@string/tv_one" android:textColor="@color/black" android:textStyle="normal" android:textSize="30sp" android:background="@color/white" android:gravity="center" /> </LinearLayout>
另外,同样,colors.xml 中可以自定义颜色,通过给自定义颜色码分配一个名字,后续使用时只需指定该颜色码对应的名字即可。
2. 带阴影的 TextView
(1)android:shadowColor: 设置阴影颜色,需要与 shadowRadius 一起使用;
(2)android:shadowRadius:设置阴影的模糊程度,设为 0.1 就变成字体颜色了,建议使用 3.0;
(3)android:shadowDx:设置阴影在水平方向的偏移,就是水平方向阴影开始的横坐标位置;
(4)android:shadowDy:设置阴影在竖直方向的偏移,就是竖直方向阴影开始的纵坐标位置;
示例代码如下:
<TextView
android:id="@+id/one_tv"
android:layout_width="200dp"
android:layout_height="200dp"
android:text="@string/tv_one"
android:textColor="@color/black"
android:textStyle="normal"
android:textSize="30sp"
android:shadowColor="@color/red"
android:shadowRadius="3.0"
android:shadowDx="10.0"
android:shadowDy="10"
android:gravity="center" />
注意:
(1)如果单单设置 shadowColor 是没有任何效果的;
(2)当 shadowRadius 的值为 0.1 时,字体和阴影是基本一致的;所以,为了能达到更真实的效果,shadowRadius 一般设置成 3.0,能使阴影变得模糊。(模糊度设置)
带阴影的 TextView.png
以上,感谢阅读!
网友评论