ListView

在Android中,有三种简单的方法可以使用ListView。

使用ArrayAdapter

ArrayAdapter是最简单的适配器,它将字符串数组的内容显示在ListView中。

ListView listView = (ListView) findViewById(R.id.listView);

String[] values = new String[] { "Android", "iPhone", "WindowsMobile", "BlackBerry", "WebOS" };

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);

listView.setAdapter(adapter);

使用SimpleAdapter

SimpleAdapter可以用于将更复杂的数据绑定到ListView。

ListView listView = (ListView) findViewById(R.id.listView);

List<Map<String, String>> data = new ArrayList<Map<String, String>>();

Map<String, String> item = new HashMap<String, String>();

item.put("title", "Google");

item.put("description", "Google search");

data.add(item);

SimpleAdapter adapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2, new String[] {"title", "description"}, new int[] {android.R.id.text1, android.R.id.text2});

listView.setAdapter(adapter);

使用自定义Adapter

如果你需要更复杂的布局或行为,你可以创建自定义的Adapter。

public class MyAdapter extends ArrayAdapter<String> {

private Context context;

public MyAdapter(Context context, int resource, List<String> objects) {

super(context, resource, objects);

this.context = context;

}

@Override

public View getView(int position, View convertView, ViewGroup parent) {

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View rowView = inflater.inflate(android.R.layout.simple_list_item_1, parent, false);

TextView textView = (TextView) rowView.findViewById(android.R.id.text1);

textView.setText(getItem(position));

return rowView;

}

}

ListView listView = (ListView) findViewById(R.id.listView);

List<String> values = new ArrayList<String>();

values.add("Android");

values.add("iPhone");

values.add("WindowsMobile");

values.add("BlackBerry");

values.add("WebOS");

MyAdapter adapter = new MyAdapter(this, android.R.layout.simple_list_item_1, values);

listView.setAdapter(adapter);

以上三种方法都可以在Android中使用ListView,你可以根据你的具体需求选择合适的方法。

相关推荐
徐同保2 小时前
如何使用GitKraken把git项目迁移到另一个平台,并保存所有提交记录,例如把github上的项目,迁移到gitee
git·gitee·github
TTGGGFF1 天前
开源项目分享 : Gitee热榜项目 2025-11-24 日榜
gitee·开源
筱顾大牛1 天前
IDEA使用Gitee来创建远程仓库
java·gitee·intellij-idea
sulikey1 天前
从入门到精通:如何自己编写高质量的 .gitignore(面向工程实践)
git·gitee·编辑器·gitlab·github·gitignore·gitattributes
打小就很皮...1 天前
React 项目开发指南:脚手架搭建、Axios 封装与 Gitee 远程仓库配置
react.js·gitee·axios
little_xianzhong1 天前
把一个本地项目导入gitee创建的仓库中
大数据·elasticsearch·gitee
代码AC不AC5 天前
【Linux】版本控制器Git
linux·git·gitee
TTGGGFF6 天前
开源项目分享 : Gitee热榜项目 2025-11-19 日榜
gitee·开源
艾莉丝努力练剑6 天前
【Git:分支管理】Git 分支管理完全指南:从创建、合并到冲突解决
linux·服务器·人工智能·git·gitee·centos·分支管理
TTGGGFF8 天前
开源项目分享 : Gitee热榜项目 2025-11-17 日榜
gitee·开源