Android ViewPager+Fragment组合使用

废话就不多说了,直接开始。
1、准备好两个布局为Fragment使用
布局一:

layout_model1.xml




    

        

        

        

        

    



布局二:

layout_model2.xml






这布局我什么都没加

2、自定义两个Fragment,当然自定义多个也是可以的,不自定义也行,代码如下:
第一个Fragment

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import megvii.testfacepass.R;

public class Model1 extends Fragment {

    private View view;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.layout_model1,container,false);
        return view;
    }
}

第二个Fragment

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import megvii.testfacepass.R;

public class Model2 extends Fragment {

    private View view;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.layout_model2,container,false);
        return view;
    }
}

3、把Fragment放入到一个集合中

private List fragments = new ArrayList<>();
fragments.add(model1);
fragments.add(model2);

4、弄一个FragmentPagerAdapter来管理Fragment,代码如下:

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import java.util.List;

public class MyFragmentPagerAdapter extends FragmentPagerAdapter {

    private List mfragmentList;

    public MyFragmentPagerAdapter(FragmentManager fm, List fragmentList) {
        super(fm);
        this.mfragmentList = fragmentList;
    }

    //获取集合中的某个项
    @Override
    public Fragment getItem(int position) {
        return mfragmentList.get(position);
    }

    //返回绘制项的数目
    @Override
    public int getCount() {
        return mfragmentList.size();
    }
}

5、把Fragment和ViewPager关联起来

MyFragmentPagerAdapter myFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(),fragments);
ViewPager viewPager = findViewById(R.id.noScrollViewPager);
viewPager .setAdapter(myFragmentPagerAdapter);

效果如下:


gif_20190916_185656.gif

你可能感兴趣的:(Android ViewPager+Fragment组合使用)