利用ViewPager和Fragment實現頁卡切換

qq_41459476發表於2018-03-07

  在微信和QQ中,頁面可以通過滑動切換,在Android應用開發中,利用ViewPager和Fragment可以實現這一功能。

  開發工具:Android Studio 3.0

  程式碼示例:

  activity_a.xml(佈局):

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager_a"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></android.support.v4.view.ViewPager>

  ActivityA:

public class ActivityA extends AppCompatActivity {

    private ViewPager viewPager;
    private List<Fragment> fragmentList = new ArrayList<>();
    private FragmentM fragmentM;
    private FragmentN fragmentN;
    private MyPagerAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_activity);

        bindID();

        fragmentM = new FragmentM();
        fragmentN = new FragmentN();
        //填充資料
        fragmentList.add(fragmentM);
        fragmentList.add(fragmentN);

        adapter = new MyPagerAdapter(getSupportFragmentManager(),fragmentList);
        viewPager.setAdapter(adapter);
    }

    private void bindID() {
        viewPager = findViewById(R.id.viewpager_a);
    }
}
在這段程式碼中可能會有部分報錯,這裡要注意V4包的統一。
MyPagerAdapter:
public class MyPagerAdapter extends FragmentPagerAdapter{

    private List<Fragment> mfragmentList;

    public MyPagerAdapter(FragmentManager fm,List<Fragment> fragmentList) {
        super(fm);
        this.mfragmentList = fragmentList;
    }

    @Override
    public Fragment getItem(int position) {
        return mfragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mfragmentList.size();
    }
}


相關文章