fragment中设置ListView
时间: 2023-12-03 16:02:37 浏览: 60
在 Android 中,ListView 是一种用于显示可滚动列表的视图组件。ListView 可以显示一个由 Adapter 提供的数据源,并将每个数据项显示为一个列表项。要在 Fragment 中设置 ListView,可以按照以下步骤操作:
1. 在 Fragment 的布局文件中添加一个 ListView 组件:
```xml
<ListView
android:id="@+id/my_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
2. 在 Fragment 的 Java 代码中获取 ListView 组件的引用,并为其设置 Adapter:
```java
public class MyFragment extends Fragment {
private ListView mListView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
// Get a reference to the ListView
mListView = (ListView) rootView.findViewById(R.id.my_list_view);
// Set the ListView adapter
MyAdapter adapter = new MyAdapter(getActivity(), getData());
mListView.setAdapter(adapter);
return rootView;
}
// Create a dummy data source
private List<String> getData() {
List<String> data = new ArrayList<>();
for (int i = 0; i < 10; i++) {
data.add("Item " + i);
}
return data;
}
}
```
在这个例子中,我们先获取了 ListView 组件的引用,然后创建了一个自定义的 Adapter(MyAdapter),并将其设置为 ListView 的 Adapter。在 MyAdapter 中,我们可以根据需要自定义每个列表项的布局和内容。getData() 方法是一个简单的示例,用于创建一个包含 10 个字符串的数据源。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)