给ListView列表控件设置适配器
时间: 2024-01-16 10:05:34 浏览: 87
在Android中,ListView是最常用的列表控件之一。要给ListView设置适配器,需要完成以下几个步骤:
1. 在XML布局文件中添加ListView控件:
```
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
```
2. 在Java代码中获取ListView控件对象:
```
ListView listView = findViewById(R.id.listView);
```
3. 创建一个适配器(Adapter)对象,并将其与数据源绑定:
```
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, // 列表项的布局文件
new String[]{"item1", "item2", "item3"}); // 数据源
```
这里创建了一个简单的字符串适配器,将三个字符串作为数据源,使用系统自带的列表项布局文件android.R.layout.simple_list_item_1作为列表项的布局文件。
4. 将适配器对象设置给ListView控件:
```
listView.setAdapter(adapter);
```
这样就完成了ListView的适配器设置,列表项将会显示数据源中的内容。
阅读全文
相关推荐
















