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,你可以根据你的具体需求选择合适的方法。

相关推荐
效能革命笔记7 小时前
Gitee DevSecOps 智能版本管理:军工软件工厂的依赖治理与供应链安全方案
网络·安全·gitee
加贝哥|usun10 小时前
最佳实践分享:GitHub项目自动同步到Gitee(码云)
gitee·github
少司府13 小时前
Tools相关:深入浅出学Git
大数据·c++·git·gitee·github·仓库·分支
效能革命笔记1 天前
国内首家|Gitee Repo 通过信通院「先进级」认证:企业级制品库核心能力与选型指南
gitee
我叫张小白。1 天前
PyCharm 集成 Git 与 Gitee
git·pycharm·gitee
z200509302 天前
【linux学习】在linux下使用git提交到gitee
git·学习·gitee
效能革命笔记2 天前
企业软件供应链安全优选:Gitee CodePecker SCA核心能力与选型参考
安全·gitee
效能革命笔记3 天前
2026年开源组件治理选型:Gitee SCA如何成为一体化解决方案的推荐之选
gitee·开源
知兀8 天前
【IDEA/Pull Request】pr流程;插件gitee pull requests
gitee
idjoy9 天前
网络原因导致gitee推送不上 提示没有权限或没有库
网络·gitee