要綁定數據到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控件。