setTheme函数不能用于恢复

时间:2012-11-12 14:39:09

标签: android android-theme

我正在尝试使用基本上根据某些数据库值设置主题的setTheme函数,但问题是我已经更新了要设置主题的数据库,我需要完成()要实现的主题设置的活动。代码是 -

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        settingsDBAdapter = new SettingsDBAdapter(this);
        settingsDBAdapter.open();

        setSettingsTheme();  <<------THIS LINE WILL SET THEME
        setContentView(R.layout.layout_task_manager);

        quickAddButton = (Button) findViewById(R.id.QuickAddButtonId);
        quickAddTaskText = (EditText) findViewById(R.id.QuickAddEditTextId);

        mDBHelper = new TasksDBAdapter(this); 
        mDBHelper.open();


        fillData();
        //code to create long press on any list item and calls onCreateContextMenu method
        registerForContextMenu(getListView());
        registerButtonListenersAndSetDefaultText();


    }

public void setSettingsTheme(){
        String currentTheme = settingsDBAdapter.fetchThemeSettings("theme");
        Log.i(TAG,"settingsDBAdapter + currentTheme-->" + settingsDBAdapter + currentTheme);
        //setTheme(R.style.HoloTheme);
        if(currentTheme.trim().equalsIgnoreCase("holo")){
            Log.i(TAG, "in holo<<<<<<<<");
            setTheme(R.style.HoloTheme);
        }else if(currentTheme.trim().equalsIgnoreCase("hololight")){
            Log.i(TAG, "in hololight<<<<<<<");
            setTheme(R.style.HoloLightTheme);
        }else{
            Log.i(TAG, "iin else<<<<<<<");
            setTheme(R.style.HoloTheme);
        }
    }

我还尝试在覆盖onResume()函数后调用setSettingsTheme()函数仍然没有用.setSettingsTheme()函数中存在的Log.i总是给出正确的值。 任何人都可以帮助我理解。在此先感谢Kaushik

2 个答案:

答案 0 :(得分:6)

ContextThemeWrapper.setTheme(int)的文档说:

  

为此上下文设置基本主题。请注意,这应该被调用   在Context中实例化任何视图之前(例如之前   致电setContentView(View)inflate(int, ViewGroup))。

Theme s构造函数中读取View属性,因此在更改主题后,您将要重新创建UI。您可以在Activity中调用finish()然后调用startActivity(getIntent())来重新启动它,或者必须编写一种方法来重建每个View对象。

答案 1 :(得分:0)

首先,帽子向Raffaele提示,指出我正确的方向。

此外,我知道这是一个旧帖子,所以如果现在有更好的方法,请告诉我。

总之...

我遇到了类似的问题,试图为我的Moto360创建一个表盘。您无法更改View层次结构引用的主题实例,但可以强制该实例采用您要切换到的主题的属性。如果您获得对主题的引用并调用Resource.Theme.applyStyle(int,boolean),则目标主题的属性将应用于View引用的主题。之后,调用使视图无效将使用新样式更新UI。

例如:(活动中的某个地方......)

 Resources.Theme myTheme = SomeActivity.this.getTheme();
 View myThemedView = SomeActivity.this.findViewById(R.id.myRootView);
 myTheme.applyStyle(R.style.MyOtherTheme,true);
 myThemedView.invalidate();
 // Above, "true" clobbers existing styles, "false" preserves them
 // and attempts to add in any new attributes.

同样,我在Moto360上的表面服务上做了这件事而没有发生任何事故。我还没有在活动上试过这个。

Resources.Theme.applyStyle(int,boolean)

您可以看到我的代码here (BatmanWatchFaceService.java)