【问题标题】:Change theme dynamically then change background of a LinearLayout fails动态更改主题然后更改 LinearLayout 的背景失败
【发布时间】:2015-06-27 04:11:55
【问题描述】:

我可以根据不同选择的对话框更改主题,但我也想将一些线性布局的背景颜色更改为其他颜色,但没有生效。对布局的任何更改都不会改变,并且仍然具有主题的背景颜色。

onCreate 部分:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
    colorBackgroundBlock = prefs.getInt("colorBackgroundBlock",R.color.block_main);
    colorTheme = prefs.getInt("colorTheme", R.style.defaultTheme);
    Utils.onActivityCreateSetTheme(this, colorTheme);
    setContentView(R.layout.activity_main);

    LinearLayout freeLinearLayoutBlock = (LinearLayout)
    findViewById(R.id.freeLinearLayoutBlock);
    // **** this is what doesn't change now  *****
    freeLinearLayoutBlock.setBackgroundResource(colorBackgroundBlock);
}

我的 Utils 类:

public class Utils{
public static void changeToTheme(Activity activity)
{
    activity.finish();
    activity.startActivity(new Intent(activity, activity.getClass()));
}

public static void onActivityCreateSetTheme(Activity activity, int theme)
{
    activity.setTheme(theme);
}
}

我的主题风格示例

<style name="defaultTheme" >
    <item name="android:background">@color/background_main</item>
    <item name="android:textColor">@color/text_main</item>
</style>

我是这样称呼主题变化的:

Utils.changeToTheme(MainActivity.this);

我将主题参考保存在首选项中,以便用户在重新启动应用程序时获得他们最后选择的主题。此外,我在 LinearLayout 中有一个 imageView(设置为 .png 图像)来更改,并且 imageView 背景将更改为我想要的颜色,而不是布局的其余部分。在没有整体主题部分的情况下,这一切都对我有用,我认为添加动态主题而不是单独更改每个布局和视图可能会更容易。

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    这不会完全回答您的问题,但可以帮助您了解如何设置主题:Android Set Theme Dynamically

    要根据激活的主题设置 LinearLayout 背景,您可以使用属性。为此,请查看Android Themes, Styles and Attributes

    简体:

    <!-- values/attr.xml -->
    <resources>
        <attr name="testcolor" format="color" />
        ..
    </resources>
    
    <!-- values/styles.xml -->
    <resources>
        <style name="AppTheme.Dark" parent="Theme.AppCompat.NoActionBar">
            <item name="backgroundLinearLayout">@color/backgroundLinearLayout</item>
            ..
        </style>
        ..
    </resources>
    
    <!-- layout/layout_1.xml -->
    <LinearLayout
       ..
       android:background="?attr/backgroundLinearLayout">
    </LinearLayout>
    

    【讨论】:

      猜你喜欢
      • 2011-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-22
      • 1970-01-01
      • 2014-04-05
      相关资源
      最近更新 更多