androidandroid-recyclerviewandroid-cardviewandroid-text-color

How to change RecyclerView items color from MainActivity?


I have an app which has a recyclerview. I want to give an opportunity to the users to switch between Night and Day mode theme. I know how to change text color and background color, but in this case I can't. Actually I am unable to find the item layout variables from MainActivity. How to create an object of ViewHolder class from MainActivity? Can anyone please help me?

Here is my Adapter class:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{

    private List<ListItemModel> listItems;
    private Context context;

    public MyAdapter(List<ListItemModel> listItems, Context context) {
        this.listItems = listItems;
        this.context = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_model, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        final ListItemModel listItem = listItems.get(position);
        holder.index_number.setText(listItem.getIndexNumber());
        holder.title_name.setText(listItem.getTitle());

    }

    @Override
    public int getItemCount() {
        return listItems.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView index_number, title_name;

        public ViewHolder(View itemView) {
            super(itemView);

            index_number = (TextView) itemView.findViewById(R.id.model_text_index_id);
            title_name = (TextView) itemView.findViewById(R.id.model_text_title_id);

        }

    }
}

Solution

  • If its a single choice list, you can define an int parameter in your list and define a method in adapter

    ....
    private int selectedPosition = -1;
    
    public void setSelectedPosition(int index){
      selectedPosition  = index;
      notifyItemChanged(selectedPosition)
    }
    

    then in OnBindViewHolder do this:

     @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        final ListItemModel listItem = listItems.get(position);
    
        holder.index_number.setText(listItem.getIndexNumber());
        holder.title_name.setText(listItem.getTitle());
    
        if(position == selectedPosition){
          holder.index_number.setTextColor(MY_COLOR)
          holder.title_name.setTextColor(MY_COLOR)
        } else {
          holder.index_number.setTextColor(NORMAL_COLOR)
          holder.title_name.setTextColor(NORMAL_COLOR)
        }
    
    }
    

    For multi selected list, you can define a parameter like isChosen in your ListItemModel and change that parameter to true and false and in your OnBindViewHolder check that parameter