1. 程式人生 > >側滑開啟抽屜+tablayout橫向滑動標題

側滑開啟抽屜+tablayout橫向滑動標題

抽屜佈局加tablayout+viewpager

記住:在抽屜fragment中必須加上 android:layout_gravity="start"側滑開啟選單,start為左邊滑動開啟,end為右滑開啟

<?xml version="1.0" encoding="utf-8"?>

<android.support.v4.widget.DrawerLayout
xmlns:android=“http://schemas.android.com/apk/res/android
xmlns:tools=“http://schemas.android.com/tools
android:id="@+id/drawerlayout"
android:layout_width=“match_parent”
android:layout_height=“match_parent”
tools:context=“com.example.demo10_23.MainActivity”>

<android.support.v4.view.ViewPager
android:id="@+id/vp_banner"
android:layout_width=“match_parent”
android:layout_height=“200dp”/>
<android.support.design.widget.TabLayout
android:id="@+id/tablayout"
android:layout_width=“match_parent”
android:layout_height=“wrap_content”/>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width=“match_parent”
android:layout_height=“wrap_content”/>


</android.support.v4.widget.DrawerLayout>

主類程式碼實現效果

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控制元件
initView();
//初始化新增fragment
initViewPager();
//抽屜開啟或關閉初始化
initActionBar();
}
private void initView() {
drawerlayout = findViewById(R.id.drawerlayout);
tabLayout = findViewById(R.id.tablayout);
viewPager = findViewById(R.id.viewpager);
drawerlayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}
private void initViewPager() {
list = new ArrayList<>();
fragments = new ArrayList<>();
tabLayout.setupWithViewPager(viewPager);
list.add(“關注”);
list.add(“推薦”);
list.add(“熱點”);
list.add(“科技”);
list.add(“視訊”);
list.add(“數碼”);
list.add(“軍事”);
viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return list.get(position);
}

        @Override
        public Fragment getItem(int position) {
            MainFragment mainFragment = new MainFragment();
            Bundle bundle = new Bundle();
            bundle.putString("name1",list.get(position));
            mainFragment.setArguments(bundle);
            return mainFragment;
        }

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

//抽屜
private void initActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
toggle = new ActionBarDrawerToggle(this,drawerlayout, R.string.open,R.string.close);
toggle.syncState();
drawerlayout.addDrawerListener(toggle);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (toggle.onOptionsItemSelected(item)){
        return true;
    }else {
        return super.onOptionsItemSelected(item);
    }
}

加上一個MainFragment檔案,實現抽屜檔案