Fragment + ViewPager +TabLayout

1.添加依賴android

com.android.support:design:25.3.1ide

 

2.XML佈局文件佈局

    <android.support.design.widget.TabLayout
        android:id="@+id/TabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        ></android.support.design.widget.TabLayout>
    <android.support.v4.view.ViewPager
        android:id="@+id/ViewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/TabLayout"></android.support.v4.view.ViewPager>.net

 

3.代碼實現get

public class MainActivity extends AppCompatActivity {it

private TabLayout mTabLayout;
    private ArrayList<Fragment> mList = new ArrayList<>();
    private AFragment aFragment;
    private BFragment bFragment;
    private CFragment cFragment;
    private ViewPager mViewPager;
    private MyAdapter myAdapter;class

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }List

    private void initView(){layout

        mTabLayout = (TabLayout) findViewById(R.id.TabLayout);
        mViewPager = (ViewPager) findViewById(R.id.ViewPager);
        aFragment = new AFragment();
        bFragment = new BFragment();
        cFragment = new CFragment();
        mList.add(aFragment);
        mList.add(bFragment);
        mList.add(cFragment);
        myAdapter = new MyAdapter(getSupportFragmentManager(),mList);
        mViewPager.setAdapter(myAdapter);
        mTabLayout.setupWithViewPager(mViewPager);
        mTabLayout.getTabAt(0).setText("電影");
        mTabLayout.getTabAt(1).setText("音樂");
        mTabLayout.getTabAt(2).setText("閱讀");activity

    } }

相關文章
相關標籤/搜索