在Android开发中,BaseAdapter是一种常用的适配器,用于将数据与ListView、GridView等列表控件进行绑定。以下是一个简单的示例,展示了如何使用BaseAdapter:
public class MyAdapter extends BaseAdapter {
private Context context;
private List<String> dataList;
public MyAdapter(Context context, List<String> dataList) {
this.context = context;
this.dataList = dataList;
}
@Override
public int getCount() {
return dataList.size();
}
@Override
public Object getItem(int position) {
return dataList.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(context).inflate(R.layout.item_layout, parent, false);
viewHolder = new ViewHolder();
viewHolder.textView = convertView.findViewById(R.id.text_view);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.textView.setText(dataList.get(position));
return convertView;
}
private static class ViewHolder {
TextView textView;
}
}
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:padding="10dp"/>
public class MainActivity extends AppCompatActivity {
private ListView listView;
private List<String> dataList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.list_view);
// 添加数据
for (int i = 1; i <= 20; i++) {
dataList.add("这是第" + i + "个项目");
}
// 使用自定义Adapter
MyAdapter adapter = new MyAdapter(this, dataList);
listView.setAdapter(adapter);
}
}
通过以上示例,您可以了解如何使用BaseAdapter来实现ListView的数据绑定。您可以根据自己的需求对Adapter进行扩展和定制。
领取专属 10元无门槛券
手把手带您无忧上云