[英]Passing changing variables to RecyclerView Adapter
我有一个自定义的RecyclerView.Adapter
,用于呈现列表的布局。 在父活动中,我有两个可以从UI更改的变量。 这些参数用于呈现RecyclerView项的一部分。
我知道我可以通过Adapter构造函数传递一些数据,但这是一次性的事情。 如何将数据传递到适配器并即时更改它?
使您的适配器实现自定义接口,在其中定义用于传递/获取数据的方法。
您始终可以将所需的任何公共方法添加到适配器,然后直接调用它们。 您可以保存到您的适配器参考您的Activity
或铸铁的结果recyclerView.getAdapter()
mAdapter = new YourAdapter();
mRecyclerView.setAdapter(mAdapter);
...
mAdapter.yourCustomMethod(data);
要么
YourAdapter adapter = (YourAdapter) recyclerView.getAdapter();
...
adapter.yourCustomMethod(data);
使用DataBinding
。 使用DataBinding
您可以将类中的字段标记为@Bindable
,然后调用notifyPropertyChanged(BR.field_name)
来更新该属性的显示方式。 这是小教程:
class Test extends BaseObservable{
@Bindable
String testString;
...
public void setTestString(String newStr){
this.testString = newStr;
notifyPropertyChanged(BR.testString);
}
...
}
并在您的布局中
<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>
通过这种方式,您可以简单地遍历Test
对象的List
并调用setTestString
来更新所有视图(仅更新相关的TextView
)。 这是有关如何开始使用DataBinding的指南
在您的RecyclerView.Adapter
您有方法notifyItemChanged(int position, Object payload)
。 只需调用此方法并将更新作为payload
参数传递即可。 然后是一个onBindViewHolder(VH holder, int position, List<Object> payloads)
,您可以在其中更新视图。
那就是当您使用RecyclerView.Adapter的notifyDataSetChanged()方法(如docs此处所述 )通过您的UI 立即更新RecyclerView中的数据时。
在适配器内部,您可以添加如下方法:
public void setPropX(yourType propxVal){
mPropX = propXVal; //Set the value of you property
notifyDataSetChanged(); //Redraw all the elements
}
在您的活动中存储适配器的全局引用,然后在需要时调用上面的函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.