在fragments中使用listview
时间: 2024-04-10 17:06:47 浏览: 104
要在Fragment中使用ListView,你需要遵循以下步骤:
1. 在布局文件中添加ListView组件。例如:
```xml
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
2. 在Fragment的onCreateView方法中获取ListView的引用。例如:
```java
public class MyFragment extends Fragment {
private ListView listView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, container, false);
listView = (ListView) view.findViewById(R.id.listview);
return view;
}
}
```
3. 为ListView设置Adapter。例如:
```java
public class MyFragment extends Fragment {
private ListView listView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, container, false);
listView = (ListView) view.findViewById(R.id.listview);
// create adapter here
MyAdapter adapter = new MyAdapter(getActivity(), myList);
listView.setAdapter(adapter);
return view;
}
}
```
其中,MyAdapter是你自己创建的Adapter类,myList是你要显示在ListView中的数据列表。
4. 实现Adapter类。例如:
```java
public class MyAdapter extends ArrayAdapter<String> {
private Context context;
private List<String> list;
public MyAdapter(Context context, List<String> list) {
super(context, R.layout.list_item_layout, list);
this.context = context;
this.list = list;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.list_item_layout, parent, false);
holder = new ViewHolder();
holder.textView = (TextView) convertView.findViewById(R.id.textview);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(list.get(position));
return convertView;
}
static class ViewHolder {
TextView textView;
}
}
```
其中,list_item_layout是ListView中每个item显示的布局文件,ViewHolder是用来优化ListView性能的类。
这样,你就可以在Fragment中使用ListView了。
阅读全文