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

相关推荐
程序员小崔日记11 天前
如何将代码轻松上传到 Gitee?Git 使用全攻略!
git·gitee·上传
普通网友15 天前
Android Jetpack 之 LifeCycle 组件_android 自定义view lifecycle
android·gitee·android jetpack
笑口常开xpr18 天前
Linux 命 令 界 的 “王 炸 组 合”!Gitee 提 交 + 权 限 控 制 + 热 键 神 操,学 会 直 接 霸 屏 终 端!
linux·gitee·权限
ProgramHan21 天前
github、gitlab、gitee分别都是什么,为什么不能访问?
gitee·gitlab·github
PieroPc21 天前
用python 写的 Gitee 数据备份工具
开发语言·python·gitee
secondyoung22 天前
Git使用:Git使用问题及解决方法总结
windows·经验分享·git·vscode·gitee·github·gitcode
承渊政道22 天前
Linux系统学习【深入剖析Git的原理和使用(下)】
linux·服务器·git·学习·gitee·vim·gitcode
唐璜Taro25 天前
硬核实战:内网 Windows 环境下 Jenkins + Gitee 自动化部署 Vue2 项目
gitee·自动化·jenkins
扶苏10021 个月前
推送代码到gitee,弹出身份验证窗口,但是输入gitee账号密码,提示认证失败
git·gitee