Java 将更改的变量传递给RecyclerView适配器
我有一个自定义的Java 将更改的变量传递给RecyclerView适配器,java,android,android-recyclerview,Java,Android,Android Recyclerview,我有一个自定义的RecyclerView.Adapter,用于呈现列表的布局。在父活动中,我有两个可以从UI更改的变量。这些参数用于呈现RecyclerView项的一部分 我知道我可以通过适配器构造函数传递一些数据,但这是一次性的。如何将数据传递到适配器并动态更改它?使适配器实现自定义接口,在那里定义传递/获取数据的方法。此时您可以使用RecycleView.Adapter的notifyDataSetChanged()方法(如上所述)要立即通过用户界面更新RecyclerView中的数据。您始终
RecyclerView.Adapter
,用于呈现列表的布局。在父活动中,我有两个可以从UI更改的变量。这些参数用于呈现RecyclerView项的一部分
我知道我可以通过适配器构造函数传递一些数据,但这是一次性的。如何将数据传递到适配器并动态更改它?使适配器实现自定义接口,在那里定义传递/获取数据的方法。此时您可以使用RecycleView.Adapter的notifyDataSetChanged()方法(如上所述)要立即通过用户界面更新RecyclerView中的数据。您始终可以向适配器添加任何想要的公共方法,并直接调用它们。您可以在
活动中保存对适配器的引用
,也可以强制转换recyclerView.getAdapter()的结果
:
或
最佳方法
使用数据绑定
。使用DataBinding
可以将类中的字段标记为@Bindable
,然后调用notifyPropertyChanged(BR.field\u 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>
通过这种方式,您只需浏览测试对象的列表
,然后调用设置字符串
来更新所有视图(只更新相关的文本视图
)。
是如何开始数据绑定的指南
体面的做法
在RecyclerView.Adapter
中,您有方法notifyItemChanged(int位置,对象负载)
。只需调用此方法并将更新作为payload
参数传递。还有一个onBindViewHolder(VHHolder,int-position,List-payloads)
可以更新视图 在适配器中,您可以添加如下方法:
public void setPropX(yourType propxVal){
mPropX = propXVal; //Set the value of you property
notifyDataSetChanged(); //Redraw all the elements
}
在activity store中,创建适配器的全局引用,然后在需要时调用上述函数太好了,这是一个很好且简单的解决方案。谢谢
<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>
public void setPropX(yourType propxVal){
mPropX = propXVal; //Set the value of you property
notifyDataSetChanged(); //Redraw all the elements
}