How to use the Android adapter ListView.
To use a ListView adapter in Android, the following steps can be taken:
- Create an adapter class that inherits from BaseAdapter and implements the corresponding methods. The adapter class is primarily responsible for binding the data source with the 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;
}
}
- Add a ListView widget to the layout file.
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
- Obtain the ListView control in Activity or Fragment and set an adapter for it.
ListView listView = findViewById(R.id.list_view);
MyAdapter adapter = new MyAdapter(data);
listView.setAdapter(adapter);
Data is a collection used for storing information, which can be a List or any other type of collection.
- You can choose to set a click event listener for the ListView.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// 处理点击事件
}
});
By following the above steps, you can use the adapter to connect the data source with the ListView and display it on the interface.