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

相关推荐
blog_jenny2 天前
Android 14 、15动态申请读写权限实现 (Java)
android·java·gitee
ZZQ-ZZQ4 天前
版本控制工具——Git
git·gitee·github·版本控制·gitea
老攀呀5 天前
Git 仓库在内网与 Gitee 间迁移及同步记录
git·gitee
Kika写代码7 天前
【Android】界面布局-线性布局LinearLayout-例子
android·gitee
紫阡星影7 天前
TortoiseGit多账号切换配置
git·gitee·tortoisegit
SnXJi_7 天前
开源赋能,双驱协同:纷析云财务与进销存软件助力企业数字化转型
java·gitee·开源·开源软件
lisw0510 天前
GitHub与Gitee各是什么?它们的区别与联系是什么?
gitee·github
昇腾CANN11 天前
昇腾CANN算子共建仓CANN-Ops正式上线Gitee,首批算子已合入
gitee·cann
菜鸟xy..11 天前
Typora 小乌龟 git 上传到gitee仓库教程
git·gitee
漫天转悠11 天前
本地Git仓库SSH同步到Gitee(码云)仓库的完整指南(附:SourceTree同步仓库)
git·gitee·ssh