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/tv_code_system"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="代码设置系统自带的颜色"
android:textSize="17sp"/>
<TextView
android:id="@+id/tv_code_eight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="代码设置8位文字颜色"
android:textSize="17sp"/>
<TextView
android:id="@+id/tv_code_six"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="代码设置6位文字颜色"
android:textSize="17sp"/>
<TextView
android:id="@+id/tv_xml"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="布局文件设置6位文字颜色"
android:textColor="#00ff00"
android:textSize="17sp"/>
<TextView
android:id="@+id/tv_color_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="资源文件设置6位文字颜色"
android:textColor="@color/green"
android:textSize="17sp"/>
<TextView
android:id="@+id/tv_color_background"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="背景设置为绿色"
android:textSize="17sp"/>
<!--android:background="@color/green"-->
</LinearLayout>Java
package com.example.chapter003;
import android.graphics.Color;
import android.os.Bundle;
import android.view.WindowManager;
import android.widget.TextView;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
public class TextColorActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//隐藏状态栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_text_color);
TextView tv_code_system = findViewById(R.id.tv_code_system);
//使用系统预定义常量设置颜色
tv_code_system.setTextColor(Color.GREEN);
TextView tv_code_eight = findViewById(R.id.tv_code_eight);
//使用8位16进制数字设置颜色
tv_code_eight.setTextColor(0xff00ff00);
TextView tv_code_six = findViewById(R.id.tv_code_six);
//使用6位16进制数字设置颜色,但是因为与8位相比缺少两位
//系统自动补零,导致为透明颜色,不显示,但是有占位
tv_code_six.setTextColor(0x00ff00);
TextView tv_code_background = findViewById(R.id.tv_color_background);
//使用系统预定义常量设置字符背景颜色
tv_code_background.setBackgroundColor(Color.GREEN);
}
}以上代码分别演示了如何在Java代码和XML布局文件中设置字符颜色,其中在XML文件中可以:
1. 通过‘android:textColor="#00ff00"’设置字符颜色,使用6位16进制数字设置,数字前加“#”号;
2. 在value/color.xml文件中预定义特定字符对应颜色16进制数字,然后通过‘android:textColor="@color/green"’方法进行引用/调用;
3. 通过‘android:background="@color/green"’设置字符的背景颜色,括号内可填写6位16进制数字或预定义颜色常量。
在Activity Java文件中,则可以:1. tv_code_system.setTextColor(Color.GREEN);
2. tv_code_eight.setTextColor(0xff00ff00);//6位16进制数字会使字符透明而不显示
3. tv_code_background.setBackgroundColor(Color.GREEN);