문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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;
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top