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

相关推荐
tsyjjOvO1 天前
【Git 从入门到实战】(IDEA+Gitee 版)
git·gitee·idea
你知道“铁甲小宝”吗丶1 天前
git推送到多平台(gitee/github)
git·gitee·github
StackNoOverflow1 天前
IDEA + Git + Gitee 全流程实战:从安装、提交到解决冲突
git·gitee·intellij-idea
lpfasd1232 天前
Git/Gitee/GitHub 3 个安全凭证详解
git·gitee·github
搞程序的心海2 天前
使用 VS Code 将项目代码上传到 Gitee 的完整指南
gitee
Gust of wind2 天前
idea结合git和Gitee的初步使用
git·gitee·intellij-idea
运维全栈笔记3 天前
零基础掌握Jenkins CI/CD:Java项目自动构建与部署全流程指南
git·servlet·ci/cd·gitee·自动化·jenkins·devops
摇滚侠4 天前
Obsidian 同步项目到 Gitee
gitee
一个程序猿老马5 天前
012、远程协作:连接GitHub/Gitee与git remote
git·gitee·github
痕忆丶6 天前
将本地项目文件上传至指定的gitee空仓库
gitee