Click here to Skip to main content
15,901,122 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hell I have create an app to change the theme between Day and Night it work fine but the problem is to how to apply the theme immediately after the button clike I'm using sharedpreference to save whether it was night or day.
This is main activity:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    SharedPreferences sharepref= 
PreferenceManager.getDefaultSharedPreferences(this);
    Boolean swichter =sharepref.getBoolean(this.KEY_PREF_STRING,true);
    Toast.makeText(this,swichter.toString(),Toast.LENGTH_LONG).show();
    if (swichter.toString()=="false"){
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
        Intent intent=getIntent();
        finish();
        startActivity(intent);
    }else{
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
        Intent intent=getIntent();
        finish();
        startActivity(intent);
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_settings) {
        // launch settings activity
        startActivity(new Intent(MainActivity.this, SettingsActivity.class));
        return true;
    }

Setting Activiry :
public static final String KEY_PREF_STRING="key_vibrate";

getSupportFragmentManager().beginTransaction()
            .replace(android.R.id.content,new SettingsFragment())
            .commit();


What I have tried:

I have used this.recreate(); and Intent intent=getIntent startAcivity method!
Posted
Comments
David Crow 5-Sep-18 15:48pm    
Have you tried something akin to:

protected void onCreate(Bundle savedInstanceState) 
{
    SharedPreferences sharepref = PreferenceManager.getDefaultSharedPreferences(this);    
    Boolean swichter = sharepref.getBoolean(this.KEY_PREF_STRING,true);    
    if (swichter)
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    else
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);    
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900