繁体   English   中英

如何单击菜单并在TabLayout中打开一个新片段

[英]How to click menu and open a new fragment in TabLayout

我有一个可用于Activity的应用程序,现在需要使用TabLayout

我已经将我3个活动分为3个片段已经是中工作ViewPagerTabLayout IMG

但是现在问题出现了,当我单击菜单时,我创建了一个新的Fragment,并将其作为参数传递给文本。

该片段是在ViewPager顶部创建的,最终无法使用Tabs。

我正在按照以下代码使用Fragment Container

    public class ContainerFragment extends Fragment {

    private static TabLayoutSetupCallback mToolbarSetupCallback;
    private List<String> mTabNamesList;

    static ViewPager viewPager;
    static ContainerFragment.ItemsPagerAdapter adapter;

    public ContainerFragment() {
        // Required empty public constructor
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        if (context instanceof MainActivity) {
            mToolbarSetupCallback = (TabLayoutSetupCallback) context;
        } else {
            throw new ClassCastException(context.toString() + " must implement TabLayoutSetupCallback");
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //android.support.v4.app.Fragment fragment = null;
        //fragment = GridFragment.newInstance("6360392529587060753");

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        //Fragment 1
        android.support.v4.app.Fragment fragment = null;
        fragment = new Galeria();

        //Fragment 2
        android.support.v4.app.Fragment fragment2 = new PageFragment();


        //Fragment 3
        final String query = "Morning";//textView.getText().toString().trim();
        android.support.v4.app.Fragment fragment3  = new SearchActivity(); // replace your custom fragment class
        Bundle bundle = new Bundle();
        bundle.putString(query, query); // use as per your need
        fragment3.setArguments(bundle);

        //fragmentTransaction.addToBackStack(null);
       // fragmentTransaction.replace(R.layout.activity_search,fragment);
       // fragmentTransaction.commit();
        //View view = inflater.inflate(R.layout.fragment_container, container, false);
        //ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewPager);
        //viewPager.setAdapter(new ItemsPagerAdapter(getChildFragmentManager(), mTabNamesList));
        //mToolbarSetupCallback.setupTabLayout(viewPager);


        View view = inflater.inflate(R.layout.fragment_container, container, false);
        viewPager = (ViewPager) view.findViewById(R.id.viewPager);

        adapter = new ContainerFragment.ItemsPagerAdapter(getChildFragmentManager());
        adapter.addFrag(fragment, "ONE");
        adapter.addFrag(fragment2, "TWO");
        adapter.addFrag(fragment3, "THREE");
        viewPager.setOffscreenPageLimit(5);
        viewPager.setAdapter(adapter);
        mToolbarSetupCallback.setupTabLayout(viewPager);

        return view;
    }


    public static class ItemsPagerAdapter extends FragmentStatePagerAdapter {

        private List<String> mTabs = new ArrayList<>();
        private static List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ItemsPagerAdapter(FragmentManager fm) {
            super(fm);
            //mTabs = tabNames;
        }

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

        @Override
        public int getItemPosition(Object object) {
/*            if (object instanceof UpdateableFragment) {
                ((UpdateableFragment) object).update(updateData);
            }*/
            //don't return POSITION_NONE, avoid fragment recreation.
            return super.getItemPosition(object);
            //return POSITION_NONE;
        }

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

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }

        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        public void replaceFragment(Fragment fragment, String title, int index) {

            mFragmentList.remove(index);
            mFragmentList.add(index, fragment);
            mFragmentTitleList.add(title);


        }
    }

    public interface TabLayoutSetupCallback {
        void setupTabLayout(ViewPager viewPager);
    }
}

我的班级MainActivity

我认为我的问题或错误就在这里!

    if (savedInstanceState == null) {
        // update the main content by replacing fragments
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        FragmentTransaction transaction = fragmentManager.beginTransaction();

        transaction.replace(R.id.container, new ContainerFragment());
        transaction.commit();
    }

我的布局activity_main

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:ads="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/ad_view"
    android:fitsSystemWindows="true">



    <android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_scrollFlags="scroll|enterAlways" />

            <android.support.design.widget.TabLayout
                android:id="@+id/tab_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_scrollFlags="scroll|enterAlways"
                app:tabMode="fixed" />

        </android.support.design.widget.AppBarLayout>

<!--        <include layout="@layout/sample" />
        <include layout="@layout/content_main" />
        -->

       <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"/>



    </android.support.design.widget.CoordinatorLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:menu="@menu/activity_main_drawer"
        app:headerLayout="@layout/nav_header_main"/>


    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />
</android.support.v4.widget.DrawerLayout>

我的布局fragment_content 这是我的片段容器布局

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ContainerFragment">

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

</FrameLayout>

我已经做了所有可以想象的事情,以使新的Fragment可以在TabLayout Corretatente中打开,但是总是在上面创建它。

            android.support.v4.app.Fragment fragment3  = new SearchActivity(); // replace your custom fragment class
            String className = fragment3.getClass().getName();
            Bundle bundle = new Bundle();
            android.support.v4.app.FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
            bundle.putString(KEY_QUERY, suggestion); // use as per your need
            fragment3.setArguments(bundle);
            fragmentTransaction.addToBackStack(className);
            fragmentTransaction.replace(R.id.container,fragment3);
            fragmentTransaction.isAddToBackStackAllowed();
            fragmentTransaction.commit();

下面的代码用于打开新的Fragment,应该为其创建一个新的片段传递参数,并使用ViewPagerTabLayout内部正常打开。

请帮助我,我已经花了2天的时间来完成这项工作,但没有成功,我几乎完全更改了该应用程序,仅恢复使用没有标签的活动。

对不起我的英语不好。

尝试像这样更改您的FragmentPagerAdapter类:

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    private final List<Fragment> mFragmentList = new ArrayList<>();

    private final List<String> mFragmentTitleList = new ArrayList<>();

    public SectionsPagerAdapter(FragmentManager manager) {
        super(manager);
    }

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

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

    public void addFragment(Fragment fragment, String title, int position) {
        mFragmentList.add(position, fragment);
        mFragmentTitleList.add(position, title);
    }


    public void removeFragment(Fragment fragment, int position) {
       mFragmentList.remove(position);
        mFragmentTitleList.remove(position);
    }

    @Override
    public CharSequence getPageTitle(int position) {
       return mFragmentTitleList.get(position);
    }

}

在片段的onCreate()中添加setHasOptionsMenu(true)以在片段中添加与活动不同的选项菜单。

步骤2:现在添加onCreateOptionsMenu方法,该方法将被覆盖为:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.filter, menu);  // Use filter.xml from step 1
}

步骤3:步骤4:现在添加onOptionsItemSelected方法,通过该方法,您可以从选择添加的操作图标时使用addFragment(Fragment fragment, String title, int position)removeFragment(Fragment fragment, int position)来动态添加/删除片段。 actionBar:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if(id == R.id.action_filter){
        //Do whatever you want to do 
        //  mSectionsPagerAdapter.addFragment(new HomeFeedFragments  (), "HOME",0);
        // mSectionsPagerAdapter.addFragment(new BlankFragment(), "NEWS", 1); 

        //  viewPager.setAdapter(mSectionsPagerAdapter);

          //or
          // mSectionsPagerAdapter.removeFragment(new BlankFragment(), 1);
          //mSectionsPagerAdapter.notifyDataChange();

        return true;
    }

    return super.onOptionsItemSelected(item);
}

不要忘记调用notifyDataChange()。

对于第一次启动,您应该setAdapter:-

private void setupViewPager(ViewPager viewPager) {

mSectionsPagerAdapter.addFragment(new HomeFeedFragments(), "HOME",0);
mSectionsPagerAdapter.addFragment(new BlankFragment(), "NEWS", 1); 

viewPager.setOffscreenPageLimit(3);
viewPager.setAdapter(mSectionsPagerAdapter);

}

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM