【问题标题】:RecyclerView icon is stateless and when go to other activity it return to default stateRecyclerView 图标是无状态的,当转到其他活动时,它会返回默认状态
【发布时间】:2020-05-31 01:17:08
【问题描述】:

我的每一行都有一个 ImageView(带边框心形图标)

recyclerview。我使用此图标添加到收藏列表。当我按下这个

图像视图已更改为其他图标(完整的心形图标)。一切都好 , 但是当我去其他的时候

Activity 返回默认图标(边框心形图标)。我使用旗帜来完成这项工作。

这是我的 RecyclerView 适配器(图片 onClick 事件):

   //============== IMG ADD TO FAVORITE CLICK LISTENER ======================
        holder.imgAddFav.setOnClickListener(new View.OnClickListener() {
            boolean flag = false;

            @Override
            public void onClick(View v) {

                QuestionDatabaseAdapter databaseAdapter = new QuestionDatabaseAdapter(v.getContext());

                if (!flag) {

                    ModelQuestion question = new ModelQuestion();


                    question.setQuestionTitle(questionha.get(position).getQuestionTitle());
                    question.setQuestionDesc(questionha.get(position).getQuestionDesc());
                    question.setQuestionDate(questionha.get(position).getQuestionDate());
                    question.setQuestionAuthorName(questionha.get(position).getQuestionAuthorName());
                    question.setQuestionAuthorPic(questionha.get(position).getQuestionAuthorPic());
                    question.setQuestionDownLink(questionha.get(position).getQuestionDownLink());

                    databaseAdapter.saveQuestion(question);

                    Toast.makeText(v.getContext(), "Added !", Toast.LENGTH_SHORT).show();
                    holder.imgAddFav.setImageResource(R.drawable.ic_favorite_red_700_24dp);
                    flag = true;
                } else {
                    Toast.makeText(v.getContext(), "Removed !", Toast.LENGTH_SHORT).show();
                    holder.imgAddFav.setImageResource(R.drawable.ic_favorite_border_red_a700_24dp);
                    flag = false;
                }
            }
        });

    }

这是我的图标。

【问题讨论】:

  • 使用数据库存储状态,然后您可以检索它并显示正确的图标
  • 这个 RecyclerVeiw 用 json 填充
  • 您需要某种机制来将图标的状态存储在某处。如何做到这一点由您自己决定。

标签: android


【解决方案1】:

为了维护每个项目的状态,在你的模型类中创建一个布尔值,例如:“isClicked”,默认设置为 false,当他点击时在适配器 onclick 中设置为 true,你需要根据这个显示项目"isClicked" 属性。

if(isClicked){
//show filled heart

 }else{
 //show empty heart

}

【讨论】:

  • 你是说数据库还是 QuestionModel ?
  • @g0labi 你试过了吗?
  • 我添加了私有布尔变量 (isClicked = false) 。并为此设置 getter 和 setter。
  • @g0labi 没错!!:)
  • 但这不起作用,从 false 更改为 true 是工作,但是从 true 更改为 false 没有任何工作,虽然它没有保存图标的状态,但当我更改图标并开始到其他活动,它不保存图标状态
【解决方案2】:

它将在holder.imageView.setImageResource();恢复默认图标 为了克服这个存储添加到收藏列表中的项目,然后正确设置图像。

//this is a simple code to check whether its in favourite
//itemMap is a static HashMap<Integer,Boolean>
// make a statement like isFavorite=itemMap !=null && itemMap.get(new Integer(position) to be used in if else statement
//use the hashmap for current use. If hasgmap is null retrieve it from a database.
//you should probably do that at the constructor of the adapter
if(isInFavourites){
   holder.imageView.setImageResource(R.drawable.favouriteImage);
}else{
   holder.imageView.setImageResource(R.drawable.addFavImage);
}

使用新线程将 onClick 中最喜欢的项目存储在哈希映射和数据库中以防止可能的延迟,这始终是一种很好的做法。

按要求解释

  • 您的回收视图适配器中有一个onBIndViewHolder() 方法,它包含用于添加最喜欢的边框图像的方法holder.imgAddFav.setImageResource()
  • 每当创建回收视图项并设置带边框的图像时,适配器都会调用该函数。
  • 因此,在 imgAddFav onClick 中,您将新添加的项目保存到您已声明为实例变量的静态 hashMap 中的收藏夹中。

    //consider the hashMap as favMap;
    HashMap<Integer,Boolean> favMap;
    
    //at the constructor of the recylcer view you've to check whether you have items that you previously added to the favorite list
    public YourAdapter(/*parameters*/){
       if(favMap==null){
          favMap=new HashMap<>();
       }
       //now fill the map with stored data
       //You can use sharedpreferences or a datase
       //for an example think that postio 2 is in favorites;
       favMap.put(new Integer(2),true);
    }
    
  • 现在回到getItemHolder()。在设置 imgAddFav 图像之前,请从 hashmap 检查特定位置是否在收藏夹中。

        //set a boolean to check whether this item is in favorites
        boolean isInFavorites;
        if(favMap.contains(new Integer(position)) && favMap.get(new Integer(position){
          //the item is in the favourite list
          //set the full colored image
          holder.imgAddFav.setImageResource(R.id.coloredHeart);
          isInFavorites=true;
       }else{
          holder.imgAddFav.setImageResource(R.id.borderedHeart);
          isInFavorites=false;
       }
    
  • 现在在 onclick 不仅可以更改图像,还可以存储结果

    holder.imgAddFav.setOnClickListener(new View.OnClickListener{
         @Overrride
         public void onClick(View v){
            if(isInFavorites){
               favMap.put(new Integer(position),false);
               //save this same thing in a database or sharedPreference.Do it in a new thread.
               //if you want to save to a database
               new Thread(new Runnable{
                   @Override
                   public void run(){
                      //insert into database
                   }
               }).start();
              //or else if you want save to sharedPreference you can use edit.apply() method
              //now change the image or simply call notify datasetChanged
              notifyDatasetChanged();  
            }
         }
    });
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多