如何更改recyclerview元素的颜色?

时间:2017-12-08 10:42:07

标签: java android android-recyclerview recycler-adapter

如果字符串与QR码中的字符串匹配,我想更改cardviewRecyclerview的颜色。如果字符串匹配,我可以显示toast,但我也想在Recyclerview中更改该特定元素的颜色。

这是选择扫描项目的代码

recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getApplicationContext(), new RecyclerItemClickListener.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                   tempString = passengerDataModelList.get(position).getPnr();
                   tempClickPosi = position;
                    Intent intent = new Intent("com.google.zxing.client.android.SCAN");
                    startActivityForResult(intent, 0);

                }
            }));

现在在ActivityResult上我会得到结果:

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
            if (requestCode == 0) {
                if (resultCode == RESULT_OK) {
                    String contents = intent.getStringExtra("SCAN_RESULT");
                    String format = intent.getStringExtra("SCAN_RESULT_FORMAT");


                    if(contents.equalsIgnoreCase(tempString)){
                        Toast.makeText(this, "String MATCHED", Toast.LENGTH_SHORT).show();
///// Here I want to change the color of that item in recycler view
                    }else if(!contents.equalsIgnoreCase(tempString)){
                        Toast.makeText(this, "String NOT MATCHED", Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(this, "Error in scanning", Toast.LENGTH_SHORT).show();
                    }


                }
            }

        }

所以请帮我改变活动中特定项目的颜色。如果需要更多信息请点评。 谢谢

3 个答案:

答案 0 :(得分:1)

假设您有模型

public class PassengerData{

  //add this property
  private boolean isMatched = false;

  void setMatched(boolean matched){
        this.isMatched = matched;
  }

  boolean isMatched(){
       return isMatched;
  }

}

然后在recyclerview's bindview中验证布尔值,

boolean matched = passengerDataModelList.get(position).isMatched();
cardview.setBackgroundColor(matched ? R.color.matched_color : R.color.unmatched_color);

然后在活动

    if(contents.equalsIgnoreCase(tempString)){
                            Toast.makeText(this, "String MATCHED", Toast.LENGTH_SHORT).show();
    ///// Here I want to change the color of that item in recycler view
              // modify `isMatched` value for that item and call `notifyDataSetChanged`();
     }

答案 1 :(得分:0)

为颜色创建单独的标志,然后一旦字符串匹配特定项目的更新标志,然后通知您的适配器

答案 2 :(得分:0)

根据我的理解,我想如果String匹配,你想让背景变得丰富多彩。在RecyclerView中,您要对行进行充气,这样您的行必须具有一个布局,如果您的字符串匹配,您可以使用如下所示的布局。以下代码仅用于理解目的。相应地自定义它。在这里我根据条件改变Recycler Item的颜色,所以我写了这个条件。你可以修改它

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
if(position==0){
    holder.itemView.setBackgroundColor(Color.BLACK);
}else{
    holder.itemView.setBackgroundColor(Color.GREY);
}
holder.mTextView.setText(mDataArray.get(position));

}