图像视图状态的共享首选项

时间:2015-07-06 19:52:58

标签: android sharedpreferences

如何使用SharedPreferences或其他任何东西保存可点击的ImageView的状态或图像。我想在返回活动后显示已保存的状态。我想在某些应用程序中实现类似收藏夹按钮的东西:

在我的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);
            }
        }
    });

和我的布局:

<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" />

感谢名单

1 个答案:

答案 0 :(得分:1)

我会使用类似的东西:

       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);
       }

然后,为了设置值:

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);
            }
        }
    });