Question

I want to allow the user change the theme from the entire app by clicking a button,
So I want to know if there is a way to change the app theme within java code.

Was it helpful?

Solution

You can use the setTheme() method on a Context.

Be sure to pay attention to the note in the documentation- you need to call setTheme() before you instantiate any Views.

If you change themes while your application is open, you will need to recreate your Activity for the changes to show.

OTHER TIPS

public class ThemeSwitcher extends Activity implements OnClickListener {
    private boolean isThemeSwitch = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (isDefault() == false) {// Default theme defined in Style file.
            setTheme(android.R.style.Theme_Light);
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.theme_switcher);
        findViewById(R.id.switchTheme).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v.getId() == R.id.switchTheme) {
            switchTheme();
            isThemeSwitch = true;
            finish();
        }
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        if (isThemeSwitch) {
            Intent intent = new Intent(this, ThemeSwitcher.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }

    }

    private SharedPreferences getPreference() {
        return getSharedPreferences("theme", 0);
    }

    private void switchTheme() {
        if (isDefault()) {
            getPreference().edit().putBoolean("theme", false).commit();
        }
        else {
            getPreference().edit().putBoolean("theme", true).commit();
        }
    }

    private boolean isDefault() {
        boolean isDef = true;
        isDef = getPreference().getBoolean("theme", false);
        return isDef;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top