Search code examples
androidandroid-theme

setTheme function not working on resume


I am trying to use setTheme function which basically set theme based on some DB value but the problem is once I have updated DB with theme to be set,I need to finish() the activity for theme settings to be implemented. code being -

@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);
        }
    }

I have also tried calling setSettingsTheme() function after overriding onResume() function still of no use.Log.i present in setSettingsTheme() function gives proper value always. Can anyone please help me in my understanding. Thanks in advance,Kaushik


Solution

  • The documentation for ContextThemeWrapper.setTheme(int) says:

    Set the base theme for this context. Note that this should be called before any views are instantiated in the Context (for example before calling setContentView(View) or inflate(int, ViewGroup)).

    The Theme attributes are read in the Views constructors, so after changing the theme you'll want to recreate the UI. You can call finish() and then startActivity(getIntent()) in your Activity to restart it, or have to code a way to rebuild each and every View object.