要绑定数据到ListViewItem,可以按照以下步骤操作:
示例代码如下:
public class MyDataModel {
private String name;
private int age;
public MyDataModel(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public class MyAdapter extends BaseAdapter {
private Context context;
private List<MyDataModel> data;
public MyAdapter(Context context, List<MyDataModel> data) {
this.context = context;
this.data = data;
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
}
TextView nameTextView = convertView.findViewById(R.id.nameTextView);
TextView ageTextView = convertView.findViewById(R.id.ageTextView);
MyDataModel item = data.get(position);
nameTextView.setText(item.getName());
ageTextView.setText(String.valueOf(item.getAge()));
return convertView;
}
}
// 在Activity中设置适配器给ListView
ListView listView = findViewById(R.id.listView);
List<MyDataModel> data = new ArrayList<>();
data.add(new MyDataModel("Alice", 25));
data.add(new MyDataModel("Bob", 30));
MyAdapter adapter = new MyAdapter(this, data);
listView.setAdapter(adapter);
在这个示例中,我们首先创建了一个自定义的数据模型类MyDataModel,包含name和age字段。然后创建了一个自定义的适配器类MyAdapter,继承自BaseAdapter,并重写了getView方法,将数据绑定到ListViewItem的布局中。最后,在Activity中实例化适配器,并将其设置给ListView控件。