目录
1.TextView文本显示视图
1.1 设置文本内容
1.第一种设置方式:在xml文件中通过android:text设置文本,如下面的代码所示。
<TextView
android:id="@+id/textView_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="你好,世界!" />
2.第二种设置方式:通过引用res/values/strings.xml中的字符串常量hello_world。在通过第一种方式设置文本时会显示警告信息,大概意思是这几个字是硬编码的字符串,建议使用来自@string的资源。如果有多个地方出现同一种字符串,那么可以在strings.xml中定义再引用,这样当要改变字符串时只需要改变一个地方就行了。
//strings.xml中的部分代码
<resources>
<string name="app_name">MyApplicationForStudy</string>
<string name="hello_world">你好,世界!</string>
</resources>
//activity_main.xml中的TextView的代码
<TextView
android:id="@+id/textView_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="@string/hello_world" />
//警告信息
Hardcoded string "你好,世界!", should use `@string` resource
3.第三种设置方式:在java代码中设置文本。通过调用文本视图对象的setText方法设置文本。如下面代码所示。其中setText方法有两种参数,一种是字符串,一种是引用strings.xml中的字符串常量。
//获取名为TextView_1的文本视图
TextView textView_1 = findViewById(R.id.textView_1);
textView_1.setText("你好,世界!");//一种方式
textView_1.setText(R.string.hello_world);//另一种方式
1.2设置文本大小
1.第一种方式:通过属性android:textSize设置文本大小,主要有三种单位sp,px,dp。推荐使用sp来设置文本大小。
<TextView
android:id="@+id/textView_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="你好,世界!"
android:textSize="20sp"/>
2.第二种方式:在java代码修改文本大小。通过调用TextView的方法setTextSize设置文本大小。该方法的参数为数字,默认单位为sp。sp为Android推荐的字号单位。
TextView textView_1 = findViewById(R.id.textView_1);
textView_1.setText("你好,世界!");
textView_1.setTextSize(20);//默认单位sp
1.3设置文本颜色
1.第一种方式:通过属性Android:textColor设置文本颜色。该属性有两种设置方式,一种是六位十六进制编码如#fff000(黄色);另一种是通过引用colors.xml中的颜色常量。
<TextView
android:id="@+id/textView_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="你好,世界!"
android:textSize="20sp"
android:textColor="@color/red"/>
//colors.xml中的部分代码
<color name="red">#FFFF0000</color>
2.第二种方式:在java代码中设置文本颜色。通过TextView的方法setTextColor设置文本颜色。第一个是Color类的颜色常量,第二个是颜色编码,0x表示十六进制,FF表示透明度,EE表示红色的浓度,DD表示绿色的浓度,CC表示蓝色的浓度,一共八位。若为六位则代表透明度默认为00即该颜色是透明的看不到的。而在上面的六位则默认透明度为FF即不透明看得到。
textView_1.setTextColor(Color.RED);
textView_1.setTextColor(0xFFEEDDCC);
textView_1.setTextColor(0xFF0000);
1465

被折叠的 条评论
为什么被折叠?



