Android: 使用已保存的导航抽屉从其他片段打开下一个片段

Android: Open next Fragment from other Fragment with saved Navigation Drawer

这是我的第一个问题,请多多包涵! :D

我在我的应用程序导航抽屉中找到了一些位置,如下所示: http://s16.postimg.org/7j9tglcn9/Quick_Memo_2015_05_18_22_18_43.png

一切都很好,我从 Navigation Drawer 中选择了 2 个元素,然后切换到 fragment,Navigation Drawer 的工作方式如下: http://s10.postimg.org/44ehubiwp/Quick_Memo_2015_05_18_22_19_17.png

问题是,当我尝试通过此处的按钮从第一个片段 (1) 打开相同的片段时:

http://s17.postimg.org/4atca3133/Quick_Memo_2015_05_18_22_19_00.png

然后我转到下一个 Fragment,但导航抽屉不起作用。 来自 MainActivity.java 的带有导航抽屉的代码:

public class MainActivity extends Activity implements OnClickListener {    
protected DrawerLayout mDrawerLayout;
        private ListView mDrawerList;
        private ActionBarDrawerToggle mDrawerToggle;

        // nav drawer title
        private CharSequence mDrawerTitle;

        // used to store app title
        private CharSequence mTitle;

        // slide menu items
        private String[] navMenuTitles;
        private TypedArray navMenuIcons;

        private ArrayList<NavDrawerItem> navDrawerItems;
        private NavDrawerListAdapter adapter;

        //final Context context;

        @Override
        protected void onCreate(Bundle savedInstanceState) {

            setContentView(R.layout.activity_main);
            super.onCreate(savedInstanceState);





            mTitle = mDrawerTitle = getTitle();

            // load slide menu items
            navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

            // nav drawer icons from resources
            navMenuIcons = getResources()
                    .obtainTypedArray(R.array.nav_drawer_icons);

            mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
            mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

            navDrawerItems = new ArrayList<NavDrawerItem>();

            // adding nav drawer items to array
            //Start
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(5, -1)));
            // Home
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(0, -1), true, "1"));
            // Find People
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(1, -1), true, "1"));
            // Photos
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(2, -1), true, "1"));
            // Communities, Will add a counter here
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(3, -1), true, "1"));
            // Pages
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(4, -1), true, "1"));
            // What's hot, We  will add a counter here
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(5, -1), true, "40+"));


            // Recycle the typed array
            navMenuIcons.recycle();

            mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

            // setting the nav drawer list adapter
            adapter = new NavDrawerListAdapter(getApplicationContext(),
                    navDrawerItems);
            mDrawerList.setAdapter(adapter);

            // enabling action bar app icon and behaving it as toggle button
            getActionBar().setDisplayHomeAsUpEnabled(true);
        //  getActionBar().setHomeButtonEnabled(true);

            mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                    R.drawable.ic_drawer, //nav menu toggle icon
                    R.string.app_name, // nav drawer open - description for accessibility
                    R.string.app_name // nav drawer close - description for accessibility
            ) {
                public void onDrawerClosed(View view) {
                    getActionBar().setTitle(mTitle);
                    // calling onPrepareOptionsMenu() to show action bar icons
                    invalidateOptionsMenu();
                }

                public void onDrawerOpened(View drawerView) {
                    getActionBar().setTitle(mDrawerTitle);
                    // calling onPrepareOptionsMenu() to hide action bar icons
                    invalidateOptionsMenu();
                }
            };
            mDrawerLayout.setDrawerListener(mDrawerToggle);

            if (savedInstanceState == null) {
                // on first time display view for first nav item
                displayView(0);
            }
        }

        /**
         * Slide menu item click listener
         * */
        public class SlideMenuClickListener implements
                ListView.OnItemClickListener {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                // display view for selected nav drawer item
                displayView(position);
            }
        }

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

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {



            // toggle nav drawer on selecting action bar app icon/title
            if (mDrawerToggle.onOptionsItemSelected(item)) {
                return true;
            }

            switch (item.getItemId()) {


            case R.id.action_settings:

                 final Dialog dialog = new Dialog(this);

                  //  AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create(); //Read Update
                //    alertDialog.setTitle("hi");
                //    alertDialog.setMessage("this is my app");
                  dialog.setContentView(R.layout.o_mnie);
                  dialog.setTitle(" ");

                  Button dialogButton = (Button) dialog.findViewById(R.id.button1);

                            dialogButton.setOnClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                   dialog.dismiss();
                                    }
                                });

                  dialog.show();  //<-- See This!

                return true;

            case R.id.next_button:



                 //   previousView = (Button)findViewById(R.id.previousView);
                //    nextView = (Button) findViewById(R.id.nextView);

                    //attach onClick listeners to the buttons

                  //  previousView.setOnClickListener(this);
                 //   nextView.setOnClickListener(this);

                    //create animations
                    slide_in_left = AnimationUtils.loadAnimation(this, R.anim.slide_in_left);
                    slide_in_right = AnimationUtils.loadAnimation(this, R.anim.slide_in_right);
                    slide_out_left = AnimationUtils.loadAnimation(this, R.anim.slide_out_left);
                    slide_out_right = AnimationUtils.loadAnimation(this, R.anim.slide_out_right);

                         ViewFlipper myViewFlipper = (ViewFlipper) findViewById(R.id.myViewFlipper);


                          //set the animation for the view that enters the screen
                        //  myViewFlipper.setInAnimation(slide_in_left);
                          //set the animation for the view leaving th screen
                        //  myViewFlipper.setOutAnimation(slide_out_right);


                           myViewFlipper.showNext();



                return true;
            case R.id.previous_button:

                 ViewFlipper myViewFlipper1 = (ViewFlipper) findViewById(R.id.myViewFlipper);
                //  myViewFlipper1.setInAnimation(slide_out_left);
                //     myViewFlipper1.setOutAnimation(slide_in_right);
                myViewFlipper1.showPrevious();

                return true;

            default:
                return super.onOptionsItemSelected(item);
            }
        }


        /* *
         * Called when invalidateOptionsMenu() is triggered
         */
        @Override
        public boolean onPrepareOptionsMenu(Menu menu) {
            // if nav drawer is opened, hide the action items
            boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
            menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
            return super.onPrepareOptionsMenu(menu);
        }

        /**
         * Diplaying fragment view for selected nav drawer list item
         * */
        private void displayView(int position) {
            // update the main content by replacing fragments
            Fragment fragment = null;

            switch (position) {
            case 0:

                fragment = new Testowa();


                break;
            case 1:
                fragment = new Polsamoczynne();
                break;
            case 2:
            //  fragment = new FindPeopleFragment();
                Toast.makeText(getApplicationContext(),"Wkrótce...",Toast.LENGTH_SHORT).show();
                break;
            case 3:
            //  fragment = new PhotosFragment();
                Toast.makeText(getApplicationContext(),"Wkrótce...",Toast.LENGTH_SHORT).show();
                break;
            case 4:
            //  fragment = new Tarczaprzejazdowa();
                break;
            case 5:
            //  fragment = new Dwukomorowe();
                break;
            case 6:
            //  fragment = new WhatsHotFragment();
                Toast.makeText(getApplicationContext(),"Wkrótce...",Toast.LENGTH_SHORT).show();
                break;

            default:
                break;
            }

            if (fragment != null) {
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction()
                        .replace(R.id.frame_container, fragment).commit();






                // update selected item and title, then close the drawer
                mDrawerList.setItemChecked(position, true);
                mDrawerList.setSelection(position);
                setTitle(navMenuTitles[position]);
                mDrawerLayout.closeDrawer(mDrawerList);
            } else {
                // error in creating fragment
                Log.e("MainActivity", "Error in creating fragment");
            }
        }

    @Override
        public void setTitle(CharSequence title) {
            mTitle = title;
            getActionBar().setTitle(mTitle);
        }

        /**
         * When using the ActionBarDrawerToggle, you must call it during
         * onPostCreate() and onConfigurationChanged()...
         */

        @Override
        protected void onPostCreate(Bundle savedInstanceState) {
            super.onPostCreate(savedInstanceState);
            // Sync the toggle state after onRestoreInstanceState has occurred.
            mDrawerToggle.syncState();
        }

        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
            // Pass any configuration change to the drawer toggls
            mDrawerToggle.onConfigurationChanged(newConfig);
        }

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

        }




    }

来自第一个开关盒 0 的代码 - Testowa.java 带有按钮:

public class Testowa<T extends MainActivity> extends  Fragment{

    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
            Bundle savedInstanceState) {

     final View view = inflater.inflate(R.layout.activity_testowa, container, false);

     final  Button button1=(Button) view.findViewById(R.id.button1);

     button1.setOnClickListener(new OnClickListener(){

          @Override
         public void onClick(View v) {


              FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
                Fragment mFragment = Fragment.instantiate(getActivity(), Dwukomorowe.class.getName());
                ft.replace(android.R.id.content, mFragment);
                ft.commit();


          }

          });

 return view;
 }

这里是 Fragment Dwukomorowe.java 中的最后一个代码 - 它是 Navigation Drawer 中的第二个元素 - 当我在 Teastowa.java 中单击按钮时相同的 Fragment:

public class Dwukomorowe extends Fragment implements View.OnClickListener  {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.activity_dwukomorowe, container, false);
        //setContentView(R.layout.activity_dwukomorowe);
        this.setHasOptionsMenu(true);



          return rootView;
    } 

您好!

我不明白你试图用你的按钮实现什么。 您要打开 Dwukomorowe 碎片吗?

您可以在您的 Activity 中创建一个方法并从您的片段中调用它。

public void loadDwukomorowe() {
    getFragmentManager().beginTransaction()
            .replace(R.id.frame_container, new Dwukomorowe())
            .commit();
}

并从您的片段中调用它:

button1.setOnClickListener(new OnClickListener(){

      @Override
     public void onClick(View v) {


     ((MainActivity) getActivity()).loadDwukomorowe();


      }

});