androidandroid-studiosettext

.setText(" text ") is not working properly in android studio


I am new to android development I want to create an app that transforms light mode to dark mode I have a button called enable dark mode I want to enable the dark mode when I press that button, I turned the dark mode ON but I also want to change the text in the button to enable light mode after clicking the button. when I use the setText() method to change the text in the onclick method the text in the box changes only when I press the button 2 times but I want the text to change instantly after pressing the button for the first time Here is my java code

public class MainActivity extends AppCompatActivity {

    private Button darkmode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        darkmode = (Button) findViewById(R.id.darkmodebutton);

        darkmode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                darkmode.setText("enable light mode");
            }
        });
    }
}

can anyone help me, please here is how the app is behaving I made a gif

app behaviour


Solution

  • I think the app lifecycle resets when the theme is changed. You can use a lifecycle aware state variable to track the theme state.

    You can read more about it here.

    Boolean isLightThemeEnabled = false;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        if (savedInstanceState != null) {
            theme = savedInstanceState.getString("THEME_KEY");
        }
    
        // YOUR USUAL CODE
        // MAKE SURE TO UPDATE THE THEME STATE VARIABLE
        
    }
    
    
    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        if(!isLightThemeEnabled) {
             darkmode.setText("enable light mode");
        }
        else {
            .....
        }
    }
    
    
    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString("THEME_KEY", isLightThemeEnabled);
        
        super.onSaveInstanceState(outState);
    }