I need some help with SharedPerferences and saving the state of an ImageButton (Dragon) when it’s clicked or unclicked.
When the ImageButton is unclick it should be the R.drawable.normal (false) and when the user clicks the ImageButton it should be R.drawable.clicked (true).
When you leave the app and open it then should retain the ImageButton drawable.clicked image. I've been looking online to determine if this is a Boolean, String or setImageURI and couldn't find an answer to it.
Could somebody please advise me on the correct method for this SharePerferences and make corrects or give an example of the correct logic?
I would appreciate the help and see my code below.
public class Main extends Activity {
ImageButton Dragon;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Dragon = (ImageButton) findViewById(R.id.imageButton1);
loadPrefs();
Dragon.setOnClickListener (new OnClickListener() {
public void onClick(View v) {
savePrefs("IMGBOX", Dragon.isSelected());
if (Dragon.isSelected()){
Dragon.setSelected(false);
Dragon.setImageResource(R.drawable.clicked);
} else {
Dragon.setImageResource(R.drawable.normal);
Dragon.setSelected(true);
}
}
}
);
}
private void loadPrefs(){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
boolean imgValue = sp.getBoolean("IMGBOX", false);
if (imgValue){
Dragon.setSelected(true);
}else{
Dragon.setSelected(false);
}
}
private void savePrefs(String key, boolean value){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
edit.putBoolean(key, value);
edit.commit();
}
}
UPDATED: I was able to get it's functioning with a ToggleButton as a boolean, a selector with two states (false/true) for the state_checked. Thanks so much for the assistance Maxim Efimov!
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/image_clicked"
android:state_checked="true" />
<item android:drawable="@drawable/image_notclicked"
android:state_checked="false"/>
</selector>