单击导航抽屉中的项目时,在viewpager中切换片段

时间:2017-03-26 07:23:57

标签: android android-layout android-fragments tabs navigation-drawer

即使看到Stack Overflow上的一些问题,我也没有得到正确的答案,因而写了这个。我在View Pager中创建了一个Tab Layout。

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:layout_scrollFlags="scroll|enterAlways"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

            <android.support.design.widget.TabLayout
                android:id="@+id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:tabGravity="fill"
                app:tabMode="scrollable"
                app:tabTextAppearance="@style/TabTextAppearance"/>
        </android.support.design.widget.AppBarLayout>
        <android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            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"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/navheader"
        app:menu="@menu/menu_navigation" />
</android.support.v4.widget.DrawerLayout>

我已经从Google Code Lab Material Design编写了此代码。我的基本要求:

视图寻呼机中有六个选项卡或片段。拉动导航抽屉时也会出现相应的六个选项。当我单击抽屉中的项目编号4时,必须有一个从当前选项卡或片段到相应的第四个选项卡或片段的沼泽。

我的主要活动中的代码:

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Adding Toolbar to Main screen
        mHandler = new Handler();
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Setting ViewPager for each Tabs
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);
        // Set Tabs inside Toolbar
        TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
        tabs.setupWithViewPager(viewPager);
        // Create Navigation drawer and inlfate layout
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
        // Adding menu icon to Toolbar
        ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            VectorDrawableCompat indicator =
                    VectorDrawableCompat.create(getResources(), R.drawable.ic_menu, getTheme());
            indicator.setTint(ResourcesCompat.getColor(getResources(), R.color.white, getTheme()));
            supportActionBar.setHomeAsUpIndicator(indicator);
            supportActionBar.setDisplayHomeAsUpEnabled(true);
        }
        // Set behavior of Navigation drawer
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    // This method will trigger on item Click of navigation menu

//                    public boolean onNavigationItemSelected(MenuItem menuItem) {
//                        // Set item in checked state
//                        menuItem.setChecked(true);
//
//                        // TODO: handle navigation
//
//                        // Closing drawer on item click
//                        mDrawerLayout.closeDrawers();
//                        return true;
//                    }


                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {

                        //Check to see which item was being clicked and perform appropriate action
                        switch (menuItem.getItemId()) {
                            //Replacing the main content with ContentFragment Which is our Inbox View;
                            case R.id.nav_home:
                                navItemIndex = 0;
                                CURRENT_TAG = TAG_HOME;
                                break;
                            case R.id.nav_history:
                                navItemIndex = 1;
                                CURRENT_TAG = TAG_HISTORY;
                                break;
                            case R.id.nav_location:
                                navItemIndex = 2;
                                CURRENT_TAG = TAG_LOCATION;
                                break;
                            case R.id.nav_developments:
                                navItemIndex = 3;
                                CURRENT_TAG = TAG_DEVELOPMENTS;
                                break;
                            case R.id.nav_donations:
                                navItemIndex = 4;
                                CURRENT_TAG = TAG_DONATIONS;
                                break;
                            case R.id.nav_resources:
                                navItemIndex = 5;
                                CURRENT_TAG = TAG_RESOURCES;
                                break;
                            case R.id.nav_feedback:
                                navItemIndex = 6;
                                CURRENT_TAG = TAG_FEEDBACK;
                                break;
                            case R.id.nav_contactus:
                                navItemIndex = 7;
                                CURRENT_TAG = TAG_CONTACTUS;
                                break;

                            default:
                                navItemIndex = 0;
                        }

                        //Checking if the item is in checked state or not, if not make it in checked state
                        if (menuItem.isChecked()) {
                            menuItem.setChecked(false);
                        } else {
                            menuItem.setChecked(true);
                        }
                        menuItem.setChecked(true);

                        loadHomeFragment();

                        return true;
                    }
                });
        // Adding Floating Action Button to bottom right of main view

    }

    private void loadHomeFragment() {

        // if user select the current navigation menu again, don't do anything
        // just close the navigation drawer
        if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
            mDrawerLayout.closeDrawers();

            // show or hide the fab button

            return;
        }

        // Sometimes, when fragment has huge data, screen seems hanging
        // when switching between navigation menus
        // So using runnable, the fragment is loaded with cross fade effect
        // This effect can be seen in GMail app
        Runnable mPendingRunnable = new Runnable() {
            @Override
            public void run() {
                // update the main content by replacing fragments



                Fragment fragment = getHomeFragment();
                FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

                fragmentTransaction.replace(R.id.viewpager, fragment, CURRENT_TAG);
                fragmentTransaction.commitAllowingStateLoss();
            }
        };

        // If mPendingRunnable is not null, then add to the message queue
        if (mPendingRunnable != null) {
            mHandler.post(mPendingRunnable);
        }

        // show or hide the fab button


        //Closing drawer on item click
        mDrawerLayout.closeDrawers();


    }



    private Fragment getHomeFragment() {
        switch (navItemIndex) {
            case 0:
                // home
                one_main oneMain = new one_main();
                return oneMain;
            case 1:
                // photos
                one_fragment oneFragment = new one_fragment();
                return oneFragment;
            case 2:
                // movies fragment
                two_location twoLocation = new two_location();
                return twoLocation;
            case 3:
                // notifications fragment
                four_future fourFuture = new four_future();
                return fourFuture;

            case 4:
                // settings fragment
                three_donation threeDonation = new three_donation();
                return threeDonation;

            case 5:
                // movies fragment
                six_download sixDownload = new six_download();
                return sixDownload;
            case 6:
                // notifications fragment
                five_feedback fiveFeedback = new five_feedback();
                return fiveFeedback;

            case 7:
                // settings fragment
                seven_contact sevenContact = new seven_contact();
                return sevenContact;
            default:
                return new one_main();
        }
    }

我可以打开我的应用。 我可以在Tabs之间导航。 我能够拉出抽屉布局。 但是,当我点击抽屉中的任何项目时,都会切换到相应的选项卡。但是标签中的所有内容都变空了。怎么解决这个问题?

或者是否有更好的解决方案来切换在抽屉布局中点击的项目?如果是,请指出详细的教程。

3 个答案:

答案 0 :(得分:1)

我能够通过使用以下代码来解决问题:

viewPager.setCurrentItem(navItemIndex)

在navigationView.setNavigationItemSelectedListener

答案 1 :(得分:0)

我希望,它可以帮到你

@Override
public boolean onNavigationItemSelected(MenuItem item) {
    int id = item.getItemId();
    displayView(id);
    return true;
}

public void displayView(int viewId) {

    Fragment fragment = null;

    switch (viewId) {
        case R.id.nav_home:
            fragment = new HomeFragment();
            txtToolbarTitle.setText(getResources().getString(R.string.ac_home));
            break;
        case R.id.nav_budget:
            fragment = new BudgetFragment();
            txtToolbarTitle.setText(getResources().getString(R.string.ac_budget));
            break;
        case R.id.nav_asset:
            fragment = new AssetFragment();
            txtToolbarTitle.setText(getResources().getString(R.string.ac_asset));
            fab.hide();
            break;
        case R.id.nav_note:
            fragment = new NotesFragment();
            txtToolbarTitle.setText(getResources().getString(R.string.ac_note));
            //toolbar.setG
            break;
        case R.id.nav_repeat:
            fragment = new RepeatFragment();
            txtToolbarTitle.setText(getResources().getString(R.string.ac_repeat));
            break;
        case R.id.nav_payment:
            fragment = new PaymentPlanFragment();
            txtToolbarTitle.setText(getResources().getString(R.string.ac_payment));
            break;
        case R.id.nav_setting:
            fragment = new SettingFragment();
            txtToolbarTitle.setText(getResources().getString(R.string.ac_setting));
            break;
    }

    if (fragment != null) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.containerView, fragment);
        ft.commit();
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
}

答案 2 :(得分:0)

InshaAllah,这将解决您的问题。 (您可以直接跳到step3)

第1步:制作一个简单的tabLayout,将其附加到viewPager,并在交换viewPager时更改片段。 (请参见YouTube教程:https://www.youtube.com/watch?v=ZnhSbXuJaqQ)。

Step2:制作一个导航抽屉。在其项目上添加onclick。 (YouTube教程:https://www.youtube.com/watch?v=HEDHabooHO0

第3步:在第一个导航项上写上viewPager.setCurrentItem(0); viewPager.setCurrentItem(01);在第二个导航项目上 第三个导航项目上的viewPager.setCurrentItem(02); 。 。 。 直到n-1次。 n表示您拥有的碎片数量。

原因: 您还记得在第一步中,负责在viewPager中切换片段的代码是: viewPager.setCurrentItem(tab.getPosition());。还有

tab.getPosition()负责确定您要移动到的片段的编号。 因此,我在这些小括号中写了0、01、02,而不是。