Fragment+TabLayout+Viewpager顶部菜单栏+遇到的坑

先把代码放上

package com.xcf.admin.couldclass.Activitys.Main;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Switch;

import com.xcf.admin.couldclass.Activitys.Base.BaseFragment;
import com.xcf.admin.couldclass.Activitys.Exam.ExamAddActivity;
import com.xcf.admin.couldclass.R;

import java.util.ArrayList;
import java.util.List;

import static io.vov.vitamio.utils.Log.TAG;

/**
 * Created by mayiyahei on 2019/1/10.
 */

public class FragmentStudy3 extends BaseFragment implements ViewPager.OnPageChangeListener{


    private ViewPager my_viewpager;
    private TabLayout my_tab;
    private List fragments;
    private List titles;
    private View myview;
    private Menu Mmenu;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (myview == null) {
            myview = inflater.inflate(R.layout.fragment_study, container, false);
        }
        initView();
        return myview;
    }

    private void initView() {
        my_tab=(TabLayout) myview.findViewById(R.id.my_tab);
        my_viewpager=(ViewPager) myview.findViewById(R.id.my_viewpager);
        fragments=new ArrayList<>();       //碎片的集合
        fragments.add(new FragmentStudy());
        fragments.add(new FragmentStudy4());

        titles=new ArrayList<>();
        titles.add("顺序练习");//标题的集合
        titles.add("随机练习");


        MyAdapter adapter=new MyAdapter(getChildFragmentManager());
        my_viewpager.setAdapter(adapter);
        my_tab.setupWithViewPager(my_viewpager);    //关联TabLayout和ViewPager
        my_viewpager.addOnPageChangeListener(this);

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);  // 这是关键的一句
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        Mmenu = menu;
        menu.clear();
        inflater.inflate(R.menu.add_study_menu, menu);//加载menu文件到布局
//        Intent intent = new Intent(getActivity(), ExamAddActivity.class);
//        startActivity(intent);
    }


    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        // 动态设置ToolBar状态
        switch (my_viewpager.getCurrentItem()) {
            case 0:
                menu.findItem(R.id.save_select_ter).setVisible(true);
                break;
            case 1:
                menu.findItem(R.id.save_select_ter).setVisible(false);
                break;
        }
        super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        // getWindow().invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
        switch (position){
            case 0:
                getActivity().invalidateOptionsMenu();
                Log.e(TAG, "onPageSelected: 进入的是0界面" );
                break;
            case 1:
                getActivity().invalidateOptionsMenu();
                Log.e(TAG, "onPageSelected: 进入的是1界面" );
                break;
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.save_select_ter:
                //Toast.makeText(getActivity(), "你点击了 添加!", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getActivity(), ExamAddActivity.class);
                intent.putExtra("erpapertype", "1");
                startActivityForResult(intent, 1);
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private class MyAdapter extends FragmentPagerAdapter {     //适配器
        public MyAdapter(FragmentManager fm) {
            super(fm);
        }
        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);  //返回碎片集合的第几项
        }

        @Override
        public int getCount() {
            return fragments.size();    //返回碎片集合大小
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles.get(position);    //返回标题的第几项
        }
    }
}

1.引入依赖库

compile 'com.android.support:design:25.3.1'
compile 'com.android.support:support-v4:25.3.1'

2.xml布局文件



    
        
        
        

        

    

3.Activity实现

private void initView() {
        my_tab=(TabLayout) myview.findViewById(R.id.my_tab);
        my_viewpager=(ViewPager) myview.findViewById(R.id.my_viewpager);
        fragments=new ArrayList<>();       //碎片的集合
        fragments.add(new FragmentStudy());
        fragments.add(new FragmentStudy4());

        titles=new ArrayList<>();
        titles.add("顺序练习");//标题的集合
        titles.add("随机练习");


        MyAdapter adapter=new MyAdapter(getChildFragmentManager());
        my_viewpager.setAdapter(adapter);
        my_tab.setupWithViewPager(my_viewpager);    //关联TabLayout和ViewPager
        my_viewpager.addOnPageChangeListener(this);
    }

4.适配器Adapter

private class MyAdapter extends FragmentPagerAdapter {     //适配器
        public MyAdapter(FragmentManager fm) {
            super(fm);
        }
        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);  //返回碎片集合的第几项
        }

        @Override
        public int getCount() {
            return fragments.size();    //返回碎片集合大小
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles.get(position);    //返回标题的第几项
        }
    }

5.如果android app分为4个fragment,fragment1、fragment2、fragment3、fragment4 4个页面,并且fragment1内部又拥有2个fragment页面时候,此时app的actionbar的menu菜单会混乱。解决办法是在fragment1上控制他的子界面的menu菜单:

@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        Mmenu = menu;
        menu.clear();
        inflater.inflate(R.menu.add_study_menu, menu);//加载menu文件到布局
//        Intent intent = new Intent(getActivity(), ExamAddActivity.class);
//        startActivity(intent);
    }


    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        // 动态设置ToolBar状态
        switch (my_viewpager.getCurrentItem()) {
            case 0:
                menu.findItem(R.id.save_select_ter).setVisible(true);
                break;
            case 1:
                menu.findItem(R.id.save_select_ter).setVisible(false);
                break;
        }
        super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        // getWindow().invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
        switch (position){
            case 0:
                getActivity().invalidateOptionsMenu();//此方法会回调onPrepareOptionsMenu方法;
                Log.e(TAG, "onPageSelected: 进入的是0界面" );
                break;
            case 1:
                getActivity().invalidateOptionsMenu();
                Log.e(TAG, "onPageSelected: 进入的是1界面" );
                break;
        }
    }

你可能感兴趣的:(Fragment+TabLayout+Viewpager顶部菜单栏+遇到的坑)