第一:
首先在activity_main中加入Viewpager控件
<androidx.viewpager.widget.ViewPagerandroid:layout_width="match_parent"android:layout_height="match_parent"android:id="@+id/viewPager"></androidx.viewpager.widget.ViewPager>
第二
新建三个xml布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@color/colorAccent"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/tvTitle"android:layout_gravity="center"android:layout_marginTop="@dimen/activity_horizontal_margin"android:textSize="50sp"android:id="@+id/line1"/></LinearLayout>
第三
在MainActivity中加入代码
public class MainActivity extends AppCompatActivity {private ViewPager mViewPager;private PagerAdapter mPagerAdapter;//适配器private ArrayList<View> mViews; //存放视图的数组private ArrayList<String> mtitle;//存放标题的数组@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mViewPager=findViewById(R.id.viewPager );LayoutInflater inflater = getLayoutInflater();View view1 = inflater.inflate(R.layout.item_page1, null);View view2 = inflater.inflate(R.layout.item_page2, null);View view3 = inflater.inflate(R.layout.item_page3, null);mViews = new ArrayList<View>();mViews.add(view1);mViews.add(view2);mViews.add(view3);mPagerAdapter=new ViewPageAdapter(mViews);mViewPager.setAdapter(mPagerAdapter);//设置适配器}}
ViewPageAdapter中有一个带参数的构造方法,里面放四个方法
public class ViewPageAdapter extends PagerAdapter {private ArrayList<View> mViewlist;public ViewPageAdapter() {}public ViewPageAdapter(ArrayList<View> viewlist) {mViewlist = viewlist;}@Override //返回要滑动的VIew的个数public int getCount() {return mViewlist.size();}@Override //来判断pager的一个view是否和instantiateItem方法返回的object有关联public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {return view==object;}@Override //从当前container中删除指定位置(position)的View;public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {container.removeView(mViewlist.get(position));}@NonNull@Override //第一:将当前视图添加到container中,第二:返回当前Viewpublic Object instantiateItem(@NonNull ViewGroup container, int position) {container.addView(mViewlist.get(position));return mViewlist.get(position);}}
总结:创建三个页面,创建适配器,实例化适配器
在Viewpager控价中set进适配器。