在MVVM/retrofit架构中使用DataBinding设置RecyclerView行中的数据,可以按照以下步骤进行:
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
app:adapter="@{viewModel.adapter}" />
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<MyData> dataList;
public MyAdapter(List<MyData> dataList) {
this.dataList = dataList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
ItemBinding binding = ItemBinding.inflate(inflater, parent, false);
return new ViewHolder(binding);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
MyData data = dataList.get(position);
holder.bind(data);
}
@Override
public int getItemCount() {
return dataList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ItemBinding binding;
public ViewHolder(ItemBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
public void bind(MyData data) {
binding.setData(data);
binding.executePendingBindings();
}
}
}
public class MyViewModel extends ViewModel {
public ObservableList<MyData> dataList = new ObservableArrayList<>();
public MyViewModel() {
// 初始化数据
dataList.add(new MyData("Item 1"));
dataList.add(new MyData("Item 2"));
dataList.add(new MyData("Item 3"));
}
}
public class MainActivity extends AppCompatActivity {
private MyViewModel viewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
viewModel = new ViewModelProvider(this).get(MyViewModel.class);
binding.setViewModel(viewModel);
binding.setLifecycleOwner(this);
}
}
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="data"
type="com.example.MyData" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{data.name}" />
</LinearLayout>
</layout>
通过以上步骤,就可以在MVVM/retrofit架构中使用DataBinding设置RecyclerView行中的数据。每当ViewModel中的数据发生变化时,RecyclerView会自动更新对应的行布局。
领取专属 10元无门槛券
手把手带您无忧上云