Change Mainactivity for another by clicking a Switch button and keeping the change

Asked

Viewed 80 times

0

I need that when I click on a Switch Button, the Mainactivity.kt is replaced by another Activity called Activitydois.java and that the option is maintained. And only if the user clicks the Switch Button again, the original Mainactivity.kt is restored.


Question: How to exchange Mainactivty for another class and maintain this option even by restarting the app?


Mainactivity.kt

class Mainactivity : Appcompatactivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
}

Activitydois.java

public class ActivityDois extends AppCompatActivity {

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

 }
  • Good morning buddy, you just have to save the state of Activity. Follow link that will help you a lot. How to save

1 answer

0


Of the many possible ways, I would use SharedPreferences.

Check your switch button and save which type you want to keep through preferences.

 Switch swt = findViewById(R.id.swt);

        if (swt.isChecked()) {
            SharedPreferences.Editor editor = getSharedPreferences("MainActivity", MODE_PRIVATE).edit();
            editor.putString("MainActivity", "ActivityDois"); 
            editor.apply();
        } else {
            SharedPreferences.Editor editor = getSharedPreferences("MainActivity", MODE_PRIVATE).edit();
            editor.putString("MainActivity", "MainActivity");
            editor.apply();
        }

And when starting the app again, check which Activity is saved as the initial

 //aqui você recupera a preferência e inicia a activity que quiser
SharedPreferences activity = getSharedPreferences("MainActivity", MODE_PRIVATE);
if(activity.equals("ActivityDois"))
//startActivity ActivityDois... 
else if(activity.equals("MainActivity"))
//startActivity MainActivity... 
  • I liked the idea. How can I reference the switch button?

  • @michaelbrayon edited the code to show

Browser other questions tagged

You are not signed in. Login or sign up in order to post.