3

I'm trying to highlight a row of my recyclerview when a user clicks on it.

Recyclerview row layout:

<data>
    <variable name="model" type="ItemRow" />
    <variable name="listener" type="ItemClickListener" />
</data>

<com.google.android.material.card.MaterialCardView       
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView            
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{model.name}"
        android:onClick="@{() -> listener.onItemClicked(model)}"           
        android:background="@{model.isSelected ? @drawable/white : @drawable/blue}"/>

</com.google.android.material.card.MaterialCardView>

The onClickListener is instantiated in the activity:

ItemClickListener listener = item -> viewModel.selectItem(item);

The viewmodel sets the isSelected property of Item to true:

public void selectItem(Item item)
{
    item.setSelected(true);        
}

However, this doesn't change the row's background. Debugging through the code shows me that the item's isSelected property is set to true. Is there something I'm missing?

user8114848
  • 173
  • 3
  • 10
  • Shouldn't you notify the adapter that the item changed? [`notifyItemChanged(`](https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#notifyItemChanged(int)). Also, any reason why you don't use selectors instead of doing it with databinding? – Fred Apr 23 '19 at 21:04
  • @Fred selectors as in the recyclerview-selection library? figured it was overkill as I just want 1 row selected. I tried using notifyItemChanged and notififydatasetchanged but it didn't seem to help – user8114848 Apr 24 '19 at 03:19
  • TBH I never heard of such library. I was referring to the Android selectors that are meant for this exact use case. There's another name for it - [StateList](https://developer.android.com/guide/topics/resources/drawable-resource#StateList) – Fred Apr 24 '19 at 05:13

1 Answers1

0

Use BaseObservable

class Item extends BaseObservable {
    private boolean isSelected = false;

    @Bindable
    public boolean getIsSelected() {
        return isSelected;
    }

    public void setSelected(Boolean isSelected) {
        this.isSelected = isSelected;
        //Probably it'll has other name, i haven't testing it
        notifyPropertyChanged(BR.selected); 
    }

}

It will works without notfiyDataSetChanged

syncended
  • 81
  • 1
  • 7