如何更改名片视图的背景色?

时间:2019-05-24 07:59:04

标签: java android

点击Cardview后,我试图更改其背景颜色。这里列出了RecyclerView中的通知历史记录。 Cardview只在该时间改变颜色。如果我返回并再次打开该应用程序,则表示它没有更改。我该怎么办?

这是我的适配器类

public class NotificationsAdapter extends RecyclerView.Adapter<NotificationsAdapter.ViewHolder> {
    public static final String TAG = "DataViewHolder";
    private Context context;

    private ArrayList<NotificationsModel> notificationsModelList;

    public NotificationsAdapter(Context context, ArrayList<NotificationsModel> notificationsModelList) {
        this.context = context;
        this.notificationsModelList = notificationsModelList;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.notification_layout, parent, false);
        Log.d(TAG, "onCreateViewHolder: ");
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        final NotificationsModel notificationsModel = notificationsModelList.get(position);
        holder.title_news.setText(notificationsModel.getTitle());
        holder.notif_message.setText(notificationsModel.getMessage());

    }

    @Override
    public int getItemCount() {
        return notificationsModelList == null ? 0 : notificationsModelList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView notif_message, title_news;

        //Initializing Views
        public ViewHolder(View itemView) {

            super(itemView);
            title_news = (TextView) itemView.findViewById(R.id.title_news);
            notif_message = (TextView) itemView.findViewById(R.id.notif_message);
            CardView cardView = (CardView) itemView.findViewById(R.id.cardViewLayoutNotif);

            itemView.findViewById(R.id.notif_message);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    cardView.setCardBackgroundColor(Color.WHITE);
                    Intent intent = new Intent(context, Newacti.class);
                    intent.putExtra("title", notificationsModelList.get(getAdapterPosition()).getTitle1());
                    intent.putExtra("body", notificationsModelList.get(getAdapterPosition()).getBody1());
                    context.startActivity(intent);
                }
            });
        }

    }
}

1 个答案:

答案 0 :(得分:2)

您可以在IsColorChanged内添加标志notificationsModel,并且每当更改cardview的颜色时,都会在模型中更新标志,

在您的onBindViewHolder中,您可以添加以下支票:

if(IsColorChanged){
    cardView.setCardBackgroundColor(Color.WHITE);
}else{
    cardView.setCardBackgroundColor(Color.BLACK);// ANY OTHER COLOR
}