亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Android 如何在所有活動中動態更改主題?

Android 如何在所有活動中動態更改主題?

開心每一天1111 2021-05-31 13:35:39
我正在嘗試在所有活動中動態切換背景主題。但是目前,我只能讓它打開開關所在的當前活動。我嘗試了以下方法:使用setTheme于其他活動集的主題,但導致的錯誤:cannot find symbol method setTheme(int):ConstraintLayout homeActivity = (ConstraintLayout) findViewById(R.id.homeLayout);homeActivity.setTheme(R.style.darktheme);也試過了getTheme,但是報錯non-static method getTheme() cannot be referenced from a static context::Resources.Theme theme = super.getTheme();theme.applyStyle(R.style.darktheme,true);請提供有關如何修復這些錯誤或替代方法的指導。更新,首選項管理器遇到的新問題:這是當前實現的,當切換黑暗主題時應該跨活動顯示,但應用程序完全變黑而沒有錯誤:myswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {        @Override        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {            if (isChecked){                PreferenceManager                        .getDefaultSharedPreferences(DisplaySettingActivity.this)                        .edit()                        .putInt("ActivityTheme", R.style.darktheme)                        .commit();                DisplaySettingActivity.this.recreate();            }
查看完整描述

2 回答

?
飲歌長嘯

TA貢獻1951條經驗 獲得超3個贊

您可以嘗試創建一個改變主題的 baseActivity,然后子類化該活動并修改您的主題。讓我知道它是否有效


查看完整回答
反對 回復 2021-06-02
?
鴻蒙傳說

TA貢獻1865條經驗 獲得超7個贊

為了擴展 Saham 的答案,這可以通過子類化 Activity 并覆蓋 onCreate() 來解決:


public class ThemeChangeActivity extends Activity {


    @Override

    public void onCreate(Bundle savedInstanceState) {

        // Gets the saved theme ID from SharedPrefs, 

        // or uses default_theme if no theme ID has been saved

        int theme = PreferenceManager.getDefaultSharedPreferences(this).getInt("ActivityTheme", R.id.default_theme);

        // Set this Activity's theme to the saved theme

        setTheme(theme);

        // Continue with creation

        super.onCreate(savedInstanceState);

    }

}

現在,從 ThemeChangeActivity 擴展所有要更改主題的活動。每當您想更改活動的主題時,您都可以使用:


PreferenceManager

    .getDefaultSharedPreferences(this)

    .edit()

    .putInt("ActivityTheme", R.id.theme_you_want_to_set)

    .commit();


查看完整回答
反對 回復 2021-06-02
  • 2 回答
  • 0 關注
  • 181 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號