如何在 recyclerview 项目中保存按钮状态

How can I save button state in recyclerview item

你好,我有一个包含一些产品的水平回收视图,我在加号按钮中将产品添加到购物车,添加产品后图标会发生变化。我这样做了,但我的问题是保存此按钮的状态,因为当我在 fragmets/activities 之间导航时和应用程序启动时按钮保持不变。这是我的:

我的适配器中的代码是:

@Override
    public void onBindViewHolder(@NonNull ArtikujtViewHolder holder, int position) {
        final Artikujt mArtikull = artikujt.get(position);

        String mArtikullName = mArtikull.getEmertimet();
        holder.artikullName.setText(mArtikullName);
        String mArtikullCmimi = mArtikull.getCmimi().toString();
        holder.artikullCmimi.setText(mArtikullCmimi+" Leke");

        holder.itemView.setOnClickListener(v -> {
            Intent intent = new Intent(mContext, ProductDetailsActivity.class);
            intent.putExtra("positon", artikujt.get(position));
            intent.putExtra("mArtikullName", mArtikullName);
            intent.putExtra("mArtikullCmimi", mArtikullCmimi);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(intent);
        });

        SharedPreferences preferences = mContext
                .getSharedPreferences(ITEMS_PREF, MODE_PRIVATE);
        SharedPreferences.Editor mEditor = preferences.edit();

        // using shared preferences to save the state
        if (preferences.contains(ITEMS_PREF)) {
            holder.addItems.setCompoundDrawablesWithIntrinsicBounds(0, 0,
                    R.drawable.ic_check_black, 0);
            holder.addItems.setEnabled(false);
        } else {

        }

        holder.addItems.setOnClickListener(v -> {
            Gson gson = new Gson();
            String json = preferences.getString("artikujtShporta", "");
            ArrayList<Artikujt> artikullObject = gson
                    .fromJson(json, new TypeToken<ArrayList<Artikujt>>(){}.getType());
            if (artikullObject != null) {
                artikullObject.add(mArtikull);
                String jsonString = gson.toJson(artikullObject);
                mEditor.putString("artikujtShporta", jsonString);
                mEditor.apply();
            } else {
                ArrayList<Artikujt> arrayArtikuj = new ArrayList<>();
                arrayArtikuj.add(mArtikull);
                Type listOfTestObject = new TypeToken<ArrayList<Artikujt>>() {}.getType();
                String s = gson.toJson(arrayArtikuj, listOfTestObject);
                mEditor.putString("artikujtShporta", s);
                mEditor.apply();
            }

             holder.addItems.setCompoundDrawablesWithIntrinsicBounds(0, 0,
              R.drawable.ic_check_black, 0);

            //======================================================================================
            // Display a toast message
            final Toast toast = Toast.makeText(mContext, R.string.shtuar_ne_shporte, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
            toast.show();
            Handler handler = new Handler();
            handler.postDelayed(toast::cancel, 1000);
            //======================================================================================

            assert artikullObject != null;
            count_key = artikullObject.size();

            String cartCount = String.valueOf(count_key);
            Intent my_intent = new Intent("msg");
            my_intent.putExtra("cart_count", cartCount);
            LocalBroadcastManager.getInstance(mContext).sendBroadcast(my_intent);

            v.setEnabled(false);
        });

    }

我搜索了很多相关内容,解决方案可能是使用共享首选项来保存状态,使用 sharedprerences.contains(preferences_id) 但我在这里感到困惑。有没有人有任何建议我怎样才能做到这一点或可能的解决方案。 提前致谢。

在大多数情况下,在模型列表中保存按钮的状态就足够了。但是,当用户更改其片段或 activity 时,您的模型列表可能会因内存使用而被系统破坏。对于这种情况,您可以选择是使用 sharedpref、file、db 等来保存数据,还是将数据保存在寿命长于 activity 或片段的存储中。您共享的页面似乎与应用程序的主要功能相关,因此您应该将数据保存在范围取决于应用程序范围的存储库中。我建议您查看 mvvm 体系结构和存储库模式。

我假设您希望 button 在单击后保持原样:

如果这是你的问题,是的,我们将使用 shared prefrences:

@Override
public void onBindViewHolder(@NonNull ArtikujtViewHolder holder, int position) {

//the item
final Artikujt mArtikull = artikujt.get(position);

..........
..........

//read the prefrences
SharedPreferences pref = getSharedPreferences("Button", MODE_PRIVATE);
String state = pref.getString(String.valueOf(position)+"pressed", "no");

if(state.equals("yes")){

//the button must be pressed, make it pressed (check mark icon)

//change the icon
holder.addItems.setCompoundDrawablesWithIntrinsicBounds(0,0,R.drawable.ic_check_black, 0);

holder.addItems.setEnabled(false);

}else{
//the button must not be pressed, make it not pressed (default add icon)

//change the icon
holder.addItems.setCompoundDrawablesWithIntrinsicBounds(0,0,R.drawable.ic_add_icon, 0);

holder.addItems.setEnabled(true);
}


//after clicking the add icon

holder.addItems.setOnClickListener(v -> {

//save to preferences
SharedPreferences.Editor editor = getSharedPreferences("Button", MODE_PRIVATE).edit();
editor.putString(String.valueOf(position)+ "pressed", "yes");
editor.apply();


//change the icon
holder.addItems.setCompoundDrawablesWithIntrinsicBounds(0,0,R.drawable.ic_check_black, 0);
            //======================================================================================
// Display a toast message
final Toast toast = Toast.makeText(mContext, R.string.shtuar_ne_shporte, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
Handler handler = new Handler();
handler.postDelayed(toast::cancel, 1000);
            //======================================================================================

assert artikullObject != null;
count_key = artikullObject.size();

String cartCount = String.valueOf(count_key);
Intent my_intent = new Intent("msg");
my_intent.putExtra("cart_count", cartCount);
LocalBroadcastManager.getInstance(mContext).sendBroadcast(my_intent);

v.setEnabled(false);

});


}