简体   繁体   中英

Passing changing variables to RecyclerView Adapter

I have a custom RecyclerView.Adapter that is used to render the layout of my list. In the parent Activity I have two variables that can be changed from the UI. These parameters are used to render part of the RecyclerView item.

I know I can pass some data via the Adapter constructor, but this is a one time thing. How can I pass data to the Adapter and change it on the fly?

使您的适配器实现自定义接口,在其中定义用于传递/获取数据的方法。

You can always add any public methods you want to your adapter and call them directly. You can either save a reference to your adapter in your Activity or cast the result of recyclerView.getAdapter() :

mAdapter = new YourAdapter();
mRecyclerView.setAdapter(mAdapter);
...
mAdapter.yourCustomMethod(data);

or

YourAdapter adapter = (YourAdapter) recyclerView.getAdapter();
...
adapter.yourCustomMethod(data);

Best approach

Use DataBinding . With DataBinding you can mark fields in your class as @Bindable and then call notifyPropertyChanged(BR.field_name) to update diplaying of just that property. Here is little tutorial:

class Test extends BaseObservable{
@Bindable
String testString;

...

    public void setTestString(String newStr){
        this.testString = newStr;
        notifyPropertyChanged(BR.testString);
    }
...
}

And in your layout

<layout
 xmlns:android="http://schemas.android.com/apk/res/android">

<data>
    <variable
        name="test"
        type="com.yout.package.name.Test"/>
</data>
<FrameLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:text="@{test.testString}"/>
</FrameLayout>
</layout>

By this way you can simply go through your List of Test objects and call setTestString to update all views (only related TextView will be updated). Here is guide to how to begin with DataBinding

Decent approach

In your RecyclerView.Adapter you have method notifyItemChanged(int position, Object payload) . Just call this method and pass your update as payload parameter. And then there is an onBindViewHolder(VH holder, int position, List<Object> payloads) where you'll can update your view.

那就是当您使用RecyclerView.Adapter的notifyDataSetChanged()方法(如docs此处所述 )通过您的UI 立即更新RecyclerView中的数据时。

Inside your adapter you can add a method like this:

public void setPropX(yourType propxVal){
    mPropX = propXVal; //Set the value of you property
    notifyDataSetChanged(); //Redraw all the elements
}

In your activity store a global reference of the adapter then call the function above when needed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM