如何动态更改主题的文本颜色?

时间:2011-05-06 07:12:34

标签: android themes

一旦用户选择不同的字体颜色,我希望更改所有TextView的文本颜色。

我可以通过链接所有相关的TextView并在它们上调用setTextColor来实现这一点。

但我想知道这是否也可以通过自定义主题来完成?

1 个答案:

答案 0 :(得分:1)

这是一个老问题, 但尽管如此, 我似乎有一个答案。

最简单的形式。

<style name="BaseTheme" parent="@android:style/Theme.Black">
    <item name="android:textColor">@color/white</item>
    <item name="android:background">@color/black</item>
</style>

<style name="InvertedTheme" parent="BaseTheme">
    <item name="android:textColor">@color/black</item>
    <item name="android:background">@color/white</item>
</style>

在你的androidmanifest集中;

<activity
  android:name=".SomeActivity"
  android:label="@string/app_name"
  android:theme="@style/BaseTheme" />

然后在你的SomeActivity.java中;

public class SomeActivity extends Activity {

  static final String INVERTED_EXTRA = "inverted";

  private void invertTheme() {
    // to make the theme take effect we need to restart the activity
    Intent inverted = new Intent(this, SomeActivity.class);
    inverted.putExtra(INVERTED_EXTRA, true);
    startActivity(inverted);
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // must be before the setContentView
    if (getIntent().getBooleanExtra(INVERTED_EXTRA, false))
      setTheme(R.style.InvertedTheme);
    }

    setContentView(R.layout.some_layout);
    ...

我在没有开始新活动的情况下尝试过, 但它没有重置颜色。

相关问题