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

相关推荐
小萌新上大分1 天前
Typora 配置 PicGo 使用 Gitee 图床实现图片自动上传(Mac 详细教程)
macos·gitee·typora图床·gitee图床·picgo配置gitee·typora配置图床·typora的图床gitee
柯南二号1 天前
【大前端】Android Deep Link 技术详解与实践指南
gitee·deeplink
南部余额2 天前
gitee设置不公开邮箱地址,推送报错解决方案
gitee
爱吃烤鸡翅的酸菜鱼3 天前
深度掌握 Git 分支体系:从基础操作到高级策略与实践案例
分布式·git·后端·gitee·github
小黄酥4 天前
Sourcetree克隆/获取gitee工程,Git获取SSH密钥
git·gitee·github
海绵宝龙7 天前
将若依(RuoYi)项目创建为私有Gitee仓库的完整步骤
前端·gitee
雾削木10 天前
通过 “移动文件 + 创建符号链接”,让 Android Studio
gitee
wei84406787212 天前
Android实现RecyclerView粘性头部效果,模拟微信账单列表的月份标题平移
android·java·微信·gitee
倔强的石头10616 天前
解决Markdown笔记图片失效问题:Gitee+PicGo图床搭建全攻略
笔记·gitee·picgo·obsidian
老黄编程18 天前
gitee.com 有raw.githubusercontent.com一样的机制吗?
gitee