本文介绍了如何从列表中获取最喜欢的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我正在尝试建立我的应用程序功能,以便用户从列表中添加项目作为收藏,并从SharedPreferences中检索数据,我将收藏夹存储到另一个活动。 我写了一个类,我正在维护添加,删除和保存收藏项目的所有方法,但问题是当我点击添加收藏夹和向下滚动到列表并返回,最喜欢的图标丢失并且总是在适配器中返回false,如果项目存在于收藏夹SharedPreferences中并且返回相应的图标,我将通过一种方法检查。 以下是我到目前为止所做的事情: 这是制作最爱功能的类别 I'm trying to established in my application feature for users to add items from list as favorite and to retrieve data from SharedPreferences where i'm storing favorites to the another activity. I have written one class where i'm maintaining all methods for adding, removing and saving items for favorites, but the problem is that when i click to add favorite and scroll down to list and come back, favorite icon losses and always returning false in adapter where i'm checking through one method if item exists in favorites SharedPreferences and returning appropriate icon for that.Here is what i have done so far:THIS IS THE CLASS FOR MAKING FUNCTIONALITY OF FAVORITESpublic class SharedPreference { public static final String PREFS_NAME = "GIFT_APP"; public static final String FAVORITES = "GIFTS"; public SharedPreference() { super(); } // THIS FOUR METHODS ARE USED FOR MAINTAINING FAVORITES. public void saveFavorite(Context context, List<GiftItem> giftItems) { SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); Gson gson = new Gson(); String jsonFavorites = gson.toJson(giftItems); editor.putString(FAVORITES, jsonFavorites); editor.apply(); } public void addFavorite(Context context, GiftItem giftItem) { List<GiftItem> favorites = getFavorites(context); if (favorites == null) { favorites = new ArrayList<>(); favorites.add(giftItem); saveFavorite(context, favorites); } } public void removeFavorite(Context context, GiftItem giftItem) { ArrayList<GiftItem> favorites = getFavorites(context); if (favorites != null) { favorites = new ArrayList<>(); favorites.remove(giftItem); saveFavorite(context, favorites); } } public ArrayList<GiftItem> getFavorites(Context context) { SharedPreferences settings; List<GiftItem> favorites; settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); if (settings.contains(FAVORITES)) { String jsonFavorites = settings.getString(FAVORITES, null); Gson gson = new Gson(); GiftItem[] favoriteItems = gson.fromJson(jsonFavorites, GiftItem[].class); favorites = Arrays.asList(favoriteItems); favorites = new ArrayList<>(favorites); } else { return null; } return (ArrayList<GiftItem>) favorites; }} 这是我设置图像视图的适配器,其中基于状态的图标应该显示,如果项目存在于最喜欢的 THIS IS THE ADAPTER WHERE I'M SETTING TO IMAGE VIEW, WHICH ICON BASED ON STATE SHOULD SHOW IF ITEM EXISTS IN FAVORITEif (checkFavoriteItem(item)) { customViewHolder.iconFavorite.setImageResource(R.drawable.ic_favorite); customViewHolder.iconFavorite.setTag("red"); } else { customViewHolder.iconFavorite.setImageResource(R.drawable.ic_add_favorite); customViewHolder.iconFavorite.setTag("red_empty"); } 如果项目对象存在于收藏中,这是适用于检查的方法 THIS IS THE METHOD IN ADAPTER FOR CHECKING IF ITEM OBJECT EXISTS IN FAVORITESpublic boolean checkFavoriteItem(GiftItem giftItem) { boolean check = false; List<GiftItem> favorites = sharedPreference.getFavorites(mContext); if (favorites != null) { for (GiftItem item : favorites) { if (item.equals(giftItem)) { check = true; break; } } } return check; } 这是我在添加项目的活动最喜欢LICK CLICK LISTENER: AND THIS IS AN ACTIVITY WHERE I'M ADDING ITEM TO FAVORITE ON LONG CLICK LISTENER:@Override public void onLongClick(View view, int position) { ImageView button = (ImageView) view.findViewById(R.id.favorite); String tag = button.getTag().toString(); if (tag.equalsIgnoreCase("red_empty")) { sharedPreference.addFavorite(HomeActivity.this, giftItems.get(position)); Toast.makeText(HomeActivity.this, "Gift added to favorite", Toast.LENGTH_SHORT).show(); button.setTag("red"); button.setImageResource(R.drawable.ic_favorite); } else { sharedPreference.removeFavorite(HomeActivity.this, giftItems.get(position)); Toast.makeText(HomeActivity.this, "Gift removed from favorite", Toast.LENGTH_SHORT).show(); button.setTag("red_empty"); button.setImageResource(R.drawable.ic_add_favorite); } } 这是一项活动,我应该看到最喜欢的项目列表: THIS IS AN ACTIVITY WHERE SHOULD I SEE LIST OF FAVORITE ITEMS:public class GiftsFavoriteList extends AppCompatActivity { RecyclerView favoriteList; SharedPreference sharedPreference; List<GiftItem> favorites; FavoriteListAdapter adapter; AVLoadingIndicatorView loadingBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gifts); initToolbar(); loadingBar = (AVLoadingIndicatorView) findViewById(R.id.loading_bar); loadingBar.setVisibility(View.GONE); // Get favorite items from SharedPreferences. sharedPreference = new SharedPreference(); favorites = sharedPreference.getFavorites(GiftsFavoriteList.this); if (favorites == null) { showAlert(getString(R.string.no_favorites_items), getString(R.string.no_favorites_msg)); } else { if (favorites.size() == 0) { showAlert(getString(R.string.no_favorites_items), getString(R.string.no_favorites_msg)); } favoriteList = (RecyclerView) findViewById(R.id.list); favoriteList.setLayoutManager(new LinearLayoutManager(this)); if (favorites != null) { adapter = new FavoriteListAdapter(this, favorites); favoriteList.setAdapter(adapter); favoriteList.addOnItemTouchListener(new RecyclerTouchListener(GiftsFavoriteList.this, favoriteList, new ClickListener() { @Override public void onClick(View view, int position) { } @Override public void onLongClick(View view, int position) { } })); } } } private void initToolbar() { Typeface font = Typeface.createFromAsset(getAssets(), "Cutie Patootie.ttf"); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); TextView titleToolbar = (TextView) toolbar.findViewById(R.id.title); titleToolbar.setTypeface(font); titleToolbar.setText(getString(R.string.toolbar_favorites)); setSupportActionBar(toolbar); } public interface ClickListener { void onClick(View view, int position); void onLongClick(View view, int position); } public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener { private GestureDetector gestureDetector; private GiftsFavoriteList.ClickListener clickListener; public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final GiftsFavoriteList.ClickListener clickListener) { this.clickListener = clickListener; gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onSingleTapUp(MotionEvent e) { return true; } @Override public void onLongPress(MotionEvent e) { View child = recyclerView.findChildViewUnder(e.getX(), e.getY()); if (child != null && clickListener != null) { clickListener.onLongClick(child, recyclerView.getChildPosition(child)); } } }); } @Override public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { View child = rv.findChildViewUnder(e.getX(), e.getY()); if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) { clickListener.onClick(child, rv.getChildPosition(child)); } return false; } @Override public void onTouchEvent(RecyclerView rv, MotionEvent e) { } @Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { } } public void showAlert(String title, String message) { AlertDialog.Builder builder = new AlertDialog.Builder(GiftsFavoriteList.this); builder.setTitle(title); builder.setMessage(message); builder.setCancelable(true); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); }} 所以我这里没有收到任何错误。当我将项目添加到收藏夹时,我只想保存状态。当我长时间点击项目时,图标改变了drawable,因为当它被添加到收藏夹时它应该看起来,但当我向下滚动到列表并返回时,它会失去该状态。So i'm not getting any error here. I just want to save state when i add item to favorites. When i long click on item, icon changed drawable for as it should looks when it's added to favorite, but it looses that state when i scroll down to list and go back up.推荐答案 你应该通过检查主键覆盖你的java bean的方法equals,我想是这样!You should overriding method "equals" of your java bean by check primary key, I think so! 注意到只有在favorites = = null时才保存到首选项。尝试向GiftItem添加唯一ID,以便您可以将其与共享首选项中的项匹配,而不是检查GiftItem.equals检查ID是否相等。Noted that you are saving to preference only if the favorites == null. Try adding a Unique ID to the GiftItem so that you can match it to the item in the share preference, instead of checking for GiftItem.equals check if the ids are equal. 这篇关于如何从列表中获取最喜欢的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-22 12:28