【问题标题】:How to Change android app theme in runtime?如何在运行时更改 android 应用程序主题?
【发布时间】:2020-08-26 18:11:14
【问题描述】:

我正在尝试在运行时更改我的应用主题

我有我的 ChangeTheme 类和 Utility(SharedPreferences) 类

ChangeTheme.java

public class ChangeTheme extends AppCompatActivity {

    private final static int THEME_LIGHT = 1;
    private final static int THEME_DARK = 2;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.change_theme_activity);
        updateTheme();
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.myoptions,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();

        switch (id){
            case R.id.theme:
                Intent toChangeTheme = new Intent(ChangeTheme.this,ChangeTheme.class);
                startActivity(toChangeTheme);
        }

        return true;
    }

    public void onRadioButtonClicked(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch(view.getId()) {
            case R.id.lightTheme:
                if (checked){
                    setTheme(R.style.AppTheme);
                }

                    break;
            case R.id.darkTheme:
                if (checked){
                    setTheme(R.style.AppThemeDark);
                }

                    break;
        }
    }

    public void updateTheme() {
        if (Utility.getTheme(getApplicationContext()) <= THEME_LIGHT) {
            setTheme(R.style.AppTheme);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimary));
            }
        } else if (Utility.getTheme(getApplicationContext()) == THEME_DARK) {
            setTheme(R.style.AppThemeDark);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                getWindow().setStatusBarColor(getResources().getColor(R.color.colorSecondary));
            }
        }
    }

}

change_theme_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="12dp"
    android:paddingLeft="8dp"
    android:paddingRight="8dp">

    <TextView
        android:id="@+id/textTheme"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Change Theme To:"
        android:layout_marginTop="125dp">
    </TextView>

    <RadioGroup
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginTop="20dp">
        <RadioButton
            android:id="@+id/lightTheme"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Light Theme"
            android:onClick="onRadioButtonClicked"/>
        <RadioButton
            android:id="@+id/darkTheme"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Dark Theme"
            android:onClick="onRadioButtonClicked"/>
    </RadioGroup>

</LinearLayout>

实用程序.java

public class Utility {
    public static void setTheme(Context context, int theme) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        prefs.edit().putInt(context.getString(R.string.prefs_theme_key), theme).apply();
    }
    public static int getTheme(Context context) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        return prefs.getInt(context.getString(R.string.prefs_theme_key), -1);
    }
}

styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="AppThemeDark" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorSecondary</item>
        <item name="colorPrimaryDark">@color/colorSecondaryDark</item>
        <item name="colorAccent">@color/colorSecondaryAccent</item>
    </style>

</resources>

当我单击按钮更改主题时,没有任何反应,为什么? 你能帮助我吗? 我已经检查过类似的问题,但没有任何帮助

2020 年 9 月 8 日更新

ChangeTheme.java

public class ChangeTheme extends AppCompatActivity {

    private final static int THEME_LIGHT = 1;
    private final static int THEME_DARK = 2;
    private RadioButton lightThemeButton;
    private RadioButton darkThemeButton;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.change_theme_activity);

        lightThemeButton = (RadioButton) findViewById(R.id.lightTheme);
        darkThemeButton = (RadioButton) findViewById(R.id.darkTheme);
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.myoptions,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();

        switch (id){
            case R.id.theme:
                Intent toChangeTheme = new Intent(ChangeTheme.this,ChangeTheme.class);
                startActivity(toChangeTheme);
        }

        return true;
    }

    public void onRadioButtonClicked(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch(view.getId()) {
            case R.id.lightTheme:
                if (checked){
                    Utility.changeToTheme(this, Utility.THEME_LIGHT);
                }
                break;
            case R.id.darkTheme:
                if (checked){
                    Utility.changeToTheme(this, Utility.THEME_DARK);
                }
                break;
        }
    }
}

实用程序.java

public class Utility {

    private static int sTheme;
    public final static int THEME_LIGHT = 0;
    public final static int THEME_DARK = 1;

    //Set the theme of the Activity, and restart it by creating a new Activity of the same type.
    public static void changeToTheme(Activity activity, int theme)
    {
        sTheme = theme;
        activity.finish();
        activity.startActivity(new Intent(activity, activity.getClass()));
    }

    //Set the theme of the activity, according to the configuration. */
    public static void onActivityCreateSetTheme(Activity activity)
    {
        switch (sTheme)
        {
            default:
            case THEME_LIGHT:
                activity.setTheme(R.style.AppTheme);
                break;
            case THEME_DARK:
                activity.setTheme(R.style.DarkTheme);
                break;
        }
    }
}

styles.xml

<color name="color_primary_grey">#212121</color>
<color name="color_primary_black">#000000</color>
<color name="color_accent_white">#aeaeae</color>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="DarkTheme" parent="AppTheme">
    <item name="colorPrimary">@color/color_primary_grey</item>
    <item name="colorPrimaryDark">@color/color_primary_black</item>
    <item name="colorAccent">@color/color_accent_white</item>
</style>

我现在要做什么才能在运行时更改主题?

【问题讨论】:

    标签: android android-layout android-activity


    【解决方案1】:

    我之前为我的应用程序这样做过。

    对于我的解决方案,我采用了this guide 中提出的方法。

    以下是要采取的步骤:

    1. 在共享首选项中保留主题的名称(或 ID)。你已经这样做了
    2. 在活动的 onCreate 方法中,获取应该应用的主题的字符串/ID(在样式中定义),如下所示:
            // inside activities onCreate method
            // Within your switch command each case should look like this
            theme.applyStyle(R.style.AppColorsDefault, true) // in Java it should be getTheme()
            // for other cases just replace the style
            theme.applyStyle(R.style.AppColorsDark, true) // true forces overwriting attributes that are -potentially - defined by your AppTheme 
    
    1. 重新启动您的活动以使您的更改生效(主题只能在您的 onCreate 方法中设置,因此您需要重新启动您的活动)
            val intent = requireActivity().intent // use Intent intent = getActivity().getIntent() in Java
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
            requireActivity().finish() // use getActivity() again
            startActivity(intent)
    

    在我的解决方案中,您也不需要继承主题。应用的样式只需要包含更改。 举个例子:

    styles.xml

    <resources>
    
        <!-- Base application theme. 
             Also consider using a Material Theme
             Theme.MaterialComponents.Light.DarkActionBar
        -->
        <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
            <!-- Customize your theme here. -->
            <!-- put all the attributes here that should be applied to the app independent from the applied colors -->
        </style>
    
        <style name="AppColorsDefault">
            <item name="colorPrimary">@color/colorPrimary</item>
            <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
            <item name="colorAccent">@color/colorAccent</item>
        </style>
    
    
        <style name="AppColorsDark">
            <item name="colorPrimary">@color/colorSecondary</item>
            <item name="colorPrimaryDark">@color/colorSecondaryDark</item>
            <item name="colorAccent">@color/colorSecondaryAccent</item>
        </style>
    
    </resources>
    

    如果您的应用程序有多个活动,并且您希望将更改的样式(例如颜色)应用于所有活动: 只需创建 BaseActivityextends AppCompatActivity 并让您的所有活动扩展此 BaseActivity

    【讨论】:

    • 好的,那么我假设您不是试图从片段中调用它?最简单的方法是在您的主要活动上调用完成。你能把你的 ChangeTheme 类变成一个片段,或者最终变成一个preference fragment compat吗?
    • 在我的回答中查看第 2 步:在活动中调用此 oncreate 方法以应用此样式。如果你想让它应用到所有的activity,那么用这个onCreate方法创建一个空的activity,让所有的activity扩展它。
    • 您的 ChangeTheme 活动不仅仅是应用主题。无需将此主题选择逻辑继承到任何其他活动。
    • 您已删除所有之前的代码。也许下次只是发布更新,以便我们可以看到您从哪里开始以及您如何找到解决问题的最终解决方案。请查看您的样式与我建议的样式。从继承自 AppCompat 主题的基本主题中分离颜色
    • 使用首选项屏幕片段而不是以前使用自定义活动的方法只是一个建议,因为它最终会使您的任务更容易。通过首选项屏幕,您还可以使用 ListPreference。你可以find an example here
    猜你喜欢
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-04
    相关资源
    最近更新 更多