在ListView中使用DataBinding,可以通过以下步骤实现:
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:items="@{viewModel.itemList}" />
public class ViewModel {
private ObservableArrayList<Item> itemList;
public ObservableArrayList<Item> getItemList() {
return itemList;
}
}
public class Item {
private String name;
private int quantity;
// getter and setter methods
}
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="item"
type="com.example.Item" />
</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="@{item.name}" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{String.valueOf(item.quantity)}" />
</LinearLayout>
</layout>
public class ItemAdapter extends BaseAdapter {
private List<Item> itemList;
private LayoutInflater inflater;
public ItemAdapter(Context context, List<Item> itemList) {
this.itemList = itemList;
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return itemList.size();
}
@Override
public Object getItem(int position) {
return itemList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
ItemBinding binding = DataBindingUtil.inflate(inflater, R.layout.item, parent, false);
convertView = binding.getRoot();
convertView.setTag(binding);
}
ItemBinding binding = (ItemBinding) convertView.getTag();
binding.setItem(itemList.get(position));
return convertView;
}
}
public class MainActivity extends AppCompatActivity {
private ViewModel viewModel;
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewModel = new ViewModel();
// 初始化ViewModel的itemList数据
listView = findViewById(R.id.listView);
listView.setAdapter(new ItemAdapter(this, viewModel.getItemList()));
}
}
通过以上步骤,就可以在ListView中使用DataBinding实现数据绑定,使每个项的数据与ViewModel中的数据源保持同步。这样,在ViewModel中更新数据时,ListView会自动更新对应的项的显示内容。
推荐的腾讯云相关产品:腾讯云移动开发平台(https://cloud.tencent.com/product/mpp)
领取专属 10元无门槛券
手把手带您无忧上云