设置文本颜色
设置文本颜色的两种方式如下:
1.XML文件设置文本颜色
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tv_color_system"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="麦芒疯狂生长!"
android:textSize="17dp"
>
</TextView>
<TextView
android:id="@+id/tv_eight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="麦芒疯狂生长!"
android:textSize="17dp"
>
</TextView>
<TextView
android:id="@+id/tv_six"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="麦芒疯狂生长!"
android:textSize="17dp"
>
</TextView>
<TextView
android:id="@+id/tv_xml"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="麦芒疯狂生长!"
android:textSize="17dp"
android:textColor="#00ff00"
>
</TextView>
<TextView
android:id="@+id/tv_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="麦芒疯狂生长!"
android:textSize="17dp"
android:textColor="@color/green"
>
</TextView>
</LinearLayout>
其中最后两个的Textview写的是通过xml设置文本颜色,android:textColor="#00ff00"采用的是6位16进制数的颜色表示方法,android:textColor="@color/green"采用的是Color类的颜色常量的颜色表示方法。
2.Java代码调用文本视图对象设置文本颜色
public class TextColorActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_color);
//设置成系统自带的颜色
TextView textView1 = findViewById(R.id.tv_color_system);
textView1.setTextColor(Color.GREEN);
//设置成8位的颜色
TextView textView2 = findViewById(R.id.tv_eight);
textView2.setTextColor(0xff00ff00);
//设置6位颜色
TextView textView3 = findViewById(R.id.tv_six);
textView3.setTextColor(0x00ff00);
}
}
因为上面的xml文件里前三个写了文本显示内容,这里只需要对颜色进行设置即可, 其中的textView1是使用的Color类的颜色常量设置颜色,textView2是使用的8位16进制数设置颜色,textView3是使用的6位16进制数设置颜色,同时如果大家想要知道为什么文本显示内容的代码要这么写,去看我文本内容设置的博客,这里不做过多解释。