Search code examples
androidandroid-layoutandroid-intentsharedpreferences

save the state of button in android


enter image description here

am working on camera application i have two imageview one is auto and second is pro i want when i click on auto auto is selected and image icon changes and when i click on pro automatically auto view deselected and pro view is selected

autobtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            autobtn.setImageResource(R.drawable.autoactive);
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ModeActivity.this);
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putString("focus_value", "focus_mode_auto");
            Intent it = new Intent(ModeActivity.this, MainActivity.class);
            startActivity(it);
            edit.commit();
            //MainActivity.grid.setVisibility(View.VISIBLE);
        }
    });

enter image description here

in the second picture pro is selected


Solution

  • You can use the SharedPreferences like this.

    SharedPreferences sharedPreferences; 
    
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ModeActivity.this);
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putBoolean("focus_value", false);
            edit.putBoolean("auto_value", false); 
            edit.commit();
    

    In your button event,

    autobtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
    
            boolean auto = edit.getBoolean("auto_value", false);
            boolean pro = edit.getBoolean("pro_value", false);
    
            if(!auto){
                edit.putBoolean("auto_value", true);
                autobtn.setImageResource(R.drawable.autoactive);
                edit.putBoolean("pro_value",false);
                probtn.setImageResource(R.drawable.xxxxx);
            }
    
            Intent it = new Intent(ModeActivity.this, MainActivity.class);
            startActivity(it);
    
        }
    });