在Android应用中,使用ViewPager和ListView可以实现水平滑动的ListItems。以下是关于如何嵌套ViewPager和ListView的代码示例:
在res/layout/
目录下创建一个名为horizontal_viewpager_listview.xml
的文件,内容如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<!-- ViewPager -->
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewPager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center"/>
<!-- ListView -->
<ListView
android:id="@+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center"/>
</LinearLayout>
创建一个名为HorizontalPagerAdapter.java
的Java文件,内容如下:
import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.ViewPager;
import java.util.ArrayList;
import java.util.List;
public class HorizontalPagerAdapter extends androidx.viewpager.widget.ViewPagerAdapter {
private List<String> items;
public HorizontalPagerAdapter(List<String> items) {
this.items = items;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
View view = LayoutInflater.from(container.getContext())
.inflate(R.layout.horizontal_viewpager_listview, container, false);
// Set the view pager as the content of the container
container.addView(view);
// Set the content of the view pager
ViewPager viewPager = view.findViewById(R.id.viewPager);
viewPager.setAdapter(new HorizontalPagerAdapter(items.get(position)));
// Set the list view as the content of the view pager
ListView listView = view.findViewById(R.id.listview);
listView.setAdapter(new ListAdapter(items.get(position)));
return view;
}
@Override
public int getCount() {
return items.size();
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
return view == o;
}
}
创建一个名为ListAdapter.java
的Java文件,内容如下:
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class ListAdapter extends ArrayAdapter<String> {
public ListAdapter(String[] items) {
super(items);
}
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
}
String item = getItem(position);
// Set the text view as the content of the list item
TextView textView = convertView.findViewById(R.id.textView);
textView.setText(item);
return convertView;
}
}
在res/layout/
目录下创建一个名为list_item.xml
的文件,内容如下:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
领取专属 10元无门槛券
手把手带您无忧上云