无法从导航栏进行片段转换

时间:2017-03-25 21:42:43

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

我创建了七个标签的标签布局。我的应用程序中还有一个导航抽屉。抽屉打开很好,但当我选择导航抽屉中的任何项目时,应用程序强制关闭.Below是我的主要Activity.Java

public class MainActivity extends AppCompatActivity {
    private static final String TAG_HOME = "home";
    private static final String TAG_HISTORY = "history";
    private static final String TAG_LOCATION = "location";
    private static final String TAG_DEVELOPMENTS = "developments";
    private static final String TAG_DONATIONS = "donations";
    private static final String TAG_FEEDBACK = "feedback";
    private static final String TAG_RESOURCES = "resources";
    private static final String TAG_CONTACTUS = "contactus";
    public static String CURRENT_TAG = TAG_HOME;
    private DrawerLayout mDrawerLayout;
    // flag to load home fragment when user presses back key
    public static int navItemIndex = 0;
    private boolean shouldLoadHomeFragOnBackPress = true;
    private Handler mHandler;
    @Override
    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);

        // Set behavior of Navigation drawer
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {


                    @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;
        }

        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.tabs, fragment, CURRENT_TAG);
                fragmentTransaction.commitAllowingStateLoss();
            }
        };

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

        mDrawerLayout.closeDrawers();

        invalidateOptionsMenu();
    }

    private Fragment getHomeFragment() {
        switch (navItemIndex) {
            case 0:
                // home
                one_main oneMain = new one_main();
                return oneMain;
            case 1:

                one_fragment oneFragment = new one_fragment();
                return oneFragment;
            case 2:

                two_location twoLocation = new two_location();
                return twoLocation;
            case 3:

                four_future fourFuture = new four_future();
                return fourFuture;

            case 4:

                three_donation threeDonation = new three_donation();
                return threeDonation;

            case 5:

                six_download sixDownload = new six_download();
                return sixDownload;
            case 6:

                five_feedback fiveFeedback = new five_feedback();
                return fiveFeedback;

            case 7:

                seven_contact sevenContact = new seven_contact();
                return sevenContact;
            default:
                return new one_main();
        }
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        } else if (id == android.R.id.home) {
            mDrawerLayout.openDrawer(GravityCompat.START);
        }
        return super.onOptionsItemSelected(item);
    }
//Checking if the item is in checked state or not, if not make it in checked state

    @Override
    public void onBackPressed() {
        if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            mDrawerLayout.closeDrawers();
            return;
        }
        if (shouldLoadHomeFragOnBackPress) {
            // checking if user is on other navigation menu
            // rather than home
            if (navItemIndex != 0) {
                navItemIndex = 0;
                CURRENT_TAG = TAG_HOME;
                loadHomeFragment();
                return;
            }
        }

        super.onBackPressed();
    }

}

我的menu_navigation.xml如下:

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_home"
       android:icon="@drawable/ic_home_black_24dp"
        android:tint="@color/button_grey"
        android:title="Home" />
    <item
        android:id="@+id/nav_history"
        android:icon="@drawable/ic_bookmark_border_black_24dp"
        android:tint="@color/button_grey"
        android:title="History" />
    <item
        android:id="@+id/nav_location"
        android:icon="@drawable/ic_bookmark_border_black_24dp"
        android:tint="@color/button_grey"
        android:title="Location" />

        <item

            android:id="@+id/nav_developments"
            android:icon="@drawable/ic_bookmark_border_black_24dp"
            android:tint="@color/button_grey"
            android:title="Developments" />
        <item
            android:id="@+id/nav_donations"
            android:icon="@drawable/ic_bookmark_border_black_24dp"
            android:tint="@color/button_grey"
            android:title="Donations" />
        <item
            android:id="@+id/nav_resources"
            android:icon="@drawable/ic_bookmark_border_black_24dp"
            android:tint="@color/button_grey"
            android:title="Resources" />
        <item
            android:id="@+id/nav_feedback"
            android:icon="@drawable/ic_bookmark_border_black_24dp"
            android:tint="@color/button_grey"
            android:title="Feedback" />

        <item
            android:id="@+id/nav_contactus"
            android:icon="@drawable/ic_bookmark_border_black_24dp"
            android:tint="@color/button_grey"
            android:title="Contact Us" />
</group>
</menu>

我的活动main.xml

<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>

有人可以告诉我应用程序关闭选择导航菜单中的任何项目的原因吗?

1 个答案:

答案 0 :(得分:0)

您的代码应如下所示:

activity_main.xml中

<?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"
  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:tabTextColor="@android:color/white"
            app:tabMode="scrollable"/>

    </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:menu="@menu/menu_navigation" />

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

片段类(我创建了一个,但您可以根据需要创建):

MyFragment.java:

package com.example.pager.view.myapplication;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MyFragment extends Fragment {

    public static MyFragment newInstance(String title) {

        Bundle args = new Bundle();
        args.putString("page_title", title);

        MyFragment fragment = new MyFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        final View inflatedView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_my, container, false);

        TextView title = (TextView) inflatedView.findViewById(R.id.title);
        title.setText(getArguments().getString("page_title"));

        return inflatedView;
    }
}

fragment_my.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"/>

</LinearLayout>

PagerAdapter.java(此类为视图寻呼机创建片段):

package com.example.pager.view.myapplication;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import java.util.List;

class PagerAdapter extends FragmentPagerAdapter {

    private final List<String> titleList;

    PagerAdapter(FragmentManager fm, List<String> titleList) {
        super(fm);
        this.titleList = titleList;
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                // here you can put different fragments for each position
                return MyFragment.newInstance(titleList.get(position));
            default:
                return MyFragment.newInstance(titleList.get(position));
        }
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        // This method return title for each fragment that will be display in tab layout
        return titleList.get(position);
    }
}

和MainActivity.java应如下所示:

package com.example.pager.view.myapplication;

import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String TAG_HOME = "home";
    private static final String TAG_HISTORY = "history";
    private static final String TAG_LOCATION = "location";
    private static final String TAG_DEVELOPMENTS = "developments";
    private static final String TAG_DONATIONS = "donations";
    private static final String TAG_FEEDBACK = "feedback";
    private static final String TAG_RESOURCES = "resources";
    private static final String TAG_CONTACTUS = "contactus";
    public static String CURRENT_TAG = TAG_HOME;

    private DrawerLayout mDrawerLayout;

    private List<String> titles = Arrays.asList(TAG_HOME, TAG_HISTORY, TAG_LOCATION, TAG_DEVELOPMENTS, TAG_DONATIONS,
            TAG_FEEDBACK, TAG_RESOURCES, TAG_CONTACTUS);
    private ViewPager viewPager;
    private PagerAdapter pagerAdapter;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        initViewPagerWithTabLayout();
        setupNavigationDrawer();
    }

    private void initViewPagerWithTabLayout() {
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        pagerAdapter = new PagerAdapter(getSupportFragmentManager(), titles);
        viewPager.setAdapter(pagerAdapter);

        TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
        tabs.setupWithViewPager(viewPager);
    }

    private void setupNavigationDrawer() {
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);

        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.nav_home:
                        CURRENT_TAG = TAG_HOME;
                        break;
                    case R.id.nav_history:
                        CURRENT_TAG = TAG_HISTORY;
                        break;
                    case R.id.nav_location:
                        CURRENT_TAG = TAG_LOCATION;
                        break;
                    case R.id.nav_developments:
                        CURRENT_TAG = TAG_DEVELOPMENTS;
                        break;
                    case R.id.nav_donations:
                        CURRENT_TAG = TAG_DONATIONS;
                        break;
                    case R.id.nav_resources:
                        CURRENT_TAG = TAG_RESOURCES;
                        break;
                    case R.id.nav_feedback:
                        CURRENT_TAG = TAG_FEEDBACK;
                        break;
                    case R.id.nav_contactus:
                        CURRENT_TAG = TAG_CONTACTUS;
                        break;
                }

                mDrawerLayout.closeDrawer(GravityCompat.START);
                viewPager.setCurrentItem(titles.indexOf(CURRENT_TAG));
                return true;
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            mDrawerLayout.openDrawer(GravityCompat.START);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            mDrawerLayout.closeDrawers();
            return;
        }

        if (viewPager.getCurrentItem() != 0) {
            viewPager.setCurrentItem(0);
            CURRENT_TAG = TAG_HOME;
            return;
        }

        super.onBackPressed();
    }
}

一切都应该很好。

祝你的应用好运!