有两种方法:
1。使用样式
您可以通过在res/values 目录中创建 XML 文件来定义自己的样式。因此,假设您想要红色和粗体文本,然后创建一个包含以下内容的文件:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyRedTheme" parent="android:Theme.Light">
<item name="android:textAppearance">@style/MyRedTextAppearance</item>
</style>
<style name="MyRedTextAppearance" parent="@android:style/TextAppearance">
<item name="android:textColor">#F00</item>
<item name="android:textStyle">bold</item>
</style>
</resources>
您可以随意命名,例如res/values/red.xml。然后,您唯一需要做的就是在所需的小部件中使用该视图,例如:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
style="@style/MyRedTheme"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is red, isn't it?"
/>
</LinearLayout>
更多参考,可以阅读这篇文章:Understanding Android Themes and Styles
2。使用自定义类
这是实现此目的的另一种可能方法,它是提供您自己的TextView,将文本颜色始终设置为您想要的任何颜色;例如:
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.widget.TextView;
public class RedTextView extends TextView{
public RedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setTextColor(Color.RED);
}
}
然后,您只需在 XML 文件中将其视为普通的TextView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<org.example.RedTextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is red, isn't it?"
/>
</LinearLayout>
您是否使用一种或另一种选择取决于您的需求。如果您只想修改外观,那么最好的方法是第一种。另一方面,如果你想改变外观并为你的小部件添加一些新功能,那么第二个就是你要走的路。