Vahidpr
Vahidpr

Reputation: 135

shared preferences on image view state

How can I save the state or the image of my clickable ImageView with SharedPreferences or anything else. I want to show the saved state after returning into the activity. I want to achieve something like the favorite button in some application :

In my MainActivity:

final ImageView like = (ImageView) findViewById(R.id.like);

    //set the click listener
    like.setOnClickListener(new OnClickListener() {

        public void onClick(View button) {
            //Set the button's appearance
            button.setSelected(!button.isSelected());

            if (button.isSelected()) {
                like.setBackgroundDrawable(null);
                like.setBackgroundResource(R.drawable.starf);

            } else {
                like.setBackgroundResource(R.drawable.star);
            }
        }
    });

and my Layout:

<ImageView
    android:id="@+id/like"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_gravity="left"
    android:paddingLeft="10dp"
    android:paddingRight="40dp"
    android:background="@drawable/star"
    android:clickable="true" />

Thanx

Upvotes: 0

Views: 635

Answers (1)

mmark
mmark

Reputation: 1204

I'd use something like:

       public void setButtonState(boolean selected){
             SharedPreferences sharedPref = getSharedPreferences();
             SharedPreferences.Editor editor = sharedPref.edit();
             editor.putBoolean(Constants.LIKE_BUTTON_STATE_SELECTED, selected);
             editor.apply();
        }

       public boolean isButtonSelected(){
         return getSharedPreferences().getBoolean(Constants.LIKE_BUTTON_STATE_SELECTED, false);
       }

Then, in order to set the value:

final ImageView like = (ImageView) findViewById(R.id.like);
like.setSelected(isButtonSelected());

//set the click listener
    like.setOnClickListener(new OnClickListener() {

        public void onClick(View button) {
            //Set the button's appearance
            button.setSelected(!button.isSelected());
            setButtonState(button.isSelected); //Here you store the value
            if (button.isSelected()) {
                like.setBackgroundDrawable(null);
                like.setBackgroundResource(R.drawable.starf);

            } else {
                like.setBackgroundResource(R.drawable.star);
            }
        }
    });

Upvotes: 1

Related Questions