Skip to content Skip to sidebar Skip to footer

How To Change List Item Appearance On Item Click.

In my application i have horizontal list view. On Item select I want to change that selected Item background color and it's text view color. i have figured out that part. But how t

Solution 1:

You basically want to make good use of your int flag, previousSelectedPosition, to keep track of the list item's position that was clicked, invoke notifyDataSetChanged(), and then set the flag as part of a conditional statement within onBindViewHolder() to update ViewHolder's views accordingly as they continuously get binded. Try the following changes:

ViewHolder's onClick():

@OverridepublicvoidonClick(View v) {
    if (itemClickListener!=null) {
        previousSelectedPosition = getAdapterPosition();

        notifyDataSetChanged();

        itemClickListener.onItemClick(v,this.getLayoutPosition(),dataType,getOldPosition());
    }
}

RecyclerView.Adapter's onBindViewHolder():

@OverridepublicvoidonBindViewHolder(ContentViewHolder holder, int position) {
    Stringname= data.get(position);
    holder.dateText.setText(name);

    if (previousSelectedPosition == position) {
        main.setBackground(ContextCompat.getDrawable(context,R.drawable.date_range_selected_item_background));
        dateText.setTextColor(ContextCompat.getColor(context,R.color.colorPrimary));
    } else {
        // TODO: Configure the FrameLayout and TextView here for initial runtime as well as back to default
    }
}

... and yes, make sure to keep previousSelectedPosition initialized as -1 for the initial runtime just so the condition in onBindViewHolder() wouldn't matter until the flag updates (after a list item is clicked, that is).

Solution 2:

Your OnClickListener does not work perfectly. You just need to implements your ViewHolder from you "ItemClickListener" interface. And add this line in onCreateViewHolder :

Viewview= inflater.inflate(R.layout.custom_date_range_list_item,parent,false);
ContentViewHoldercVh=  ContentViewHolder(view);view.setOnClickListener(newView.OnClickListener() {
        @OverridepublicvoidonClick(View v) {

            cVh.onItemClick(v,this.getLayoutPosition(),cVh .dataType,cVh .getOldPosition());

        }
    });return cVh

Post a Comment for "How To Change List Item Appearance On Item Click."