假设您的 values/styles.xml 中有一个名为 RedHUGEText 的样式:
<style name="RedHUGEText" parent="@android:style/Widget.TextView">
<item name="android:textSize">@dimen/text_size_huge</item>
<item name="android:textColor">@color/red</item>
<item name="android:textStyle">bold</item>
</style>
只需像往常一样在 XML 布局/your_layout.xml 文件中创建您的 TextView,假设:
<TextView android:id="@+id/text_view_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content
android:text="FOO" />
在你的 Activity 的 java 代码中你这样做:
TextView textViewTitle = (TextView) findViewById(R.id.text_view_title);
textViewTitle.setTextAppearance(this, R.style.RedHUGEText);
它对我有用!它应用了颜色、大小、重力等。我已经在 Android API 级别从 8 到 17 的手机和平板电脑上使用它,没有任何问题。请注意,从 Android 23 开始,该方法已被弃用。上下文参数已被删除,所以最后一行需要是:
textViewTitle.setTextAppearance(R.style.RedHUGEText);
要支持所有 API 级别,请使用 androidX TextViewCompat
TextViewCompat.setTextAppearance(textViewTitle, R.style.RedHUGEText)
请记住...仅当文本的样式确实取决于 Java 逻辑上的条件或者您正在使用代码“动态”构建 UI 时才有用...如果不是,则最好这样做:
<TextView android:id="@+id/text_view_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content
android:text="FOO"
style="@style/RedHUGEText" />
你可以随心所欲!