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 天前
版本管理系统与平台(权威资料核对、深入解析、行业选型与国产平台补充)
git·gitee·gitlab·github·svm
咖啡の猫2 天前
Android开发-常用布局
android·gitee
NewChapter °4 天前
如何通过 Gitee API 上传文件到指定仓库
前端·vue.js·gitee·uni-app
Irene19915 天前
使用gitee新建项目并上传或更新代码
gitee
Git效能管理组5 天前
本土化DevOps平台崛起:Gitee如何成为国内技术团队的首选解决方案
gitee·devsecops·gitee devops·gitee repo·gitee test·gitee wiki
Git效能管理组6 天前
国产化浪潮下,Gitee如何成为技术团队的项目管理新基建?
gitee·devsecops·gitee devops·gitee repo·gitee test·gitee wiki
偏执网友7 天前
idea上传本地项目代码到Gitee仓库教程
java·gitee·intellij-idea
王廷胡_白嫖帝8 天前
六、练习3:Gitee平台操作
gitee
王廷胡_白嫖帝8 天前
一、Git与Gitee常见问题解答
git·elasticsearch·gitee
future_studio8 天前
如何用 Android 平台开发第一个 Kotlin 小程序
android·gitee