在Android中使用ListView適配器,可以通過以下步驟實現:
public class MyAdapter extends BaseAdapter {
private List<String> mData;
public MyAdapter(List<String> data) {
mData = data;
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.textView = convertView.findViewById(R.id.text_view);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.textView.setText(mData.get(position));
return convertView;
}
private static class ViewHolder {
TextView textView;
}
}
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
ListView listView = findViewById(R.id.list_view);
MyAdapter adapter = new MyAdapter(data);
listView.setAdapter(adapter);
其中,data是一個存儲數據的集合,可以是一個List
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// 處理點擊事件
}
});
通過以上步驟,就可以使用適配器將數據源與ListView進行關聯,并顯示在界面上。