使用ActionBar.NAVIGATION_MODE_TABS时,如何在单击SlidingMenu项时更改片段

时间:2013-11-04 15:39:45

标签: android slidingmenu

我搜索但无法找到问题的确切解决方案。 我有一个使用ActionBar.NAVIGATION_MODE_TABS的MainActivity应用程序,它允许主分页器支持可滑动的Tab片段。 当我打开菜单(SlidingMenu)并单击某个项目时。我想要一个新的片段(或布局)替换主要的寻呼机布局(其中包含标签 - 片段)。 例如,打开应用程序后,我们可以看到4个标签:短信,通话,时间表,新闻。 打开SlidingMenu,我们有3个项目:设置,日历,关于。 点击设置,新内容将取代旧的。现在我们只看到一页。 我的MainActivity.java代码:

    package com.giacngumo.SMS_Call_Calendar_Tracking;

import android.util.Log;
import com.actionbarsherlock.app.ActionBar;
import android.os.Bundle;
import android.support.v4.app.*;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.actionbarsherlock.internal.app.ActionBarImpl;
import com.actionbarsherlock.internal.app.ActionBarWrapper;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.giacngumo.SMS_CallLog_Calendar_Tracking.SMS_CallLog_Calendar_Tracking.R;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class MainActivity extends SlidingFragmentActivity {

    AppSectionsPagerAdapter mAppSectionsPagerAdapter;
    ViewPager mViewPager;
    protected ListFragment mFrag;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        try {
            setTitle(R.string.title_bar_slide);

            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            // set the Behind View
            setBehindContentView(R.layout.menu_frame);
            FragmentTransaction t = this.getSupportFragmentManager().beginTransaction();
            mFrag = new MenuListFragment();
            t.replace(R.id.menu_frame, mFrag);
            t.commit();

            // configure the SlidingMenu
            final SlidingMenu slidingMenu = getSlidingMenu();
            slidingMenu.setShadowWidthRes(R.dimen.shadow_width);
            slidingMenu.setShadowDrawable(R.drawable.shadow);
            slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
            slidingMenu.setFadeDegree(0.35f);
            slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);

            // Set up the action bar.
            final ActionBar actionBar = getSupportActionBar();
            //pre-ICS
            if (actionBar instanceof ActionBarImpl) {
                enableEmbeddedTabs(actionBar);

                //ICS and forward
            } else if (actionBar instanceof ActionBarWrapper) {
                try {
                    Field actionBarField = actionBar.getClass().getDeclaredField("mActionBar");
                    actionBarField.setAccessible(true);
                    //enableEmbeddedTabs(actionBarField.get(actionBar));
                } catch (Exception e) {
                    //Log.e(TAG, "Error enabling embedded tabs", e);
                }
            }
            // Specify that the Home/Up button should not be enabled, since there is no hierarchical
            // parent.
            actionBar.setHomeButtonEnabled(true);
            actionBar.setIcon(R.drawable.hamburger_icon);

            // Specify that we will be displaying tabs in the action bar.
            actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
            actionBar.setDisplayShowTitleEnabled(false);

            // Create the adapter that will return a fragment for each of the four primary sections
            // of the app.
            mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
            // Set up the ViewPager, attaching the adapter and setting up a listener for when the
            // user swipes between sections.
            mViewPager = (ViewPager) findViewById(R.id.main_pager);
            mViewPager.setAdapter(mAppSectionsPagerAdapter);
            mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                    // When swiping between different app sections, select the corresponding tab.
                    // We can also use ActionBar.Tab#select() to do this if we have a reference to the
                    // Tab.
                    actionBar.setSelectedNavigationItem(position);
                    switch (position) {
                        case 0:
                            slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
                            break;
                        default:
                            slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
                    }
                }
            });
            // For each of the sections in the app, add a tab to the action bar.
            // Create a tab with text corresponding to the page title defined by the adapter.
            // Also specify this Activity object, which implements the TabListener interface, as the
            // listener for when this tab is selected.
            actionBar.addTab(
                    actionBar.newTab()
                            .setCustomView(R.layout.tab_sms)
                            .setTabListener(tabListener));
            actionBar.addTab(
                    actionBar.newTab()
                            .setCustomView(R.layout.tab_calllog)
                            .setTabListener(tabListener));
            actionBar.addTab(
                    actionBar.newTab()
                            .setCustomView(R.layout.tab_schedule)
                            .setTabListener(tabListener));
            actionBar.addTab(
                    actionBar.newTab()
                            .setCustomView(R.layout.tab_news)
                            .setTabListener(tabListener));
        } catch (Exception ex) {
            Log.e("error", ex.getMessage());
        }
    }

    //helper method
    private void enableEmbeddedTabs(Object actionBar) {
        try {
            Method setHasEmbeddedTabsMethod = actionBar.getClass().getDeclaredMethod("setHasEmbeddedTabs", boolean.class);
            setHasEmbeddedTabsMethod.setAccessible(true);
            setHasEmbeddedTabsMethod.invoke(actionBar, true);
        } catch (Exception e) {
            //Log.e(TAG, "Error marking actionbar embedded", e);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                toggle();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

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

    ActionBar.TabListener tabListener = new ActionBar.TabListener() {
        public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
            // When the tab is selected, switch to the
            // corresponding page in the ViewPager.
            mViewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
        }

        @Override
        public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
        }
    };

    /**
     * A {@link android.support.v4.app.FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
     * sections of the app.
     */
    public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {

        public AppSectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int i) {
            Fragment fragment = null;
            Bundle args = new Bundle();
            if (i == 0) {
                // sms case
                fragment = new Sms_ListFragment();
            } else if (i == 1) {
                // call log case
                fragment = new Call_ListFragment();
            } else if (i == 2) {
                // schedule case
                fragment = new Call_ListFragment();
            } else if (i == 3) {
                fragment = new Call_ListFragment();
            }
            return fragment;
        }

        @Override
        public int getCount() {
            return 4;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "SMS";
                case 1:
                    return "Call Log";
                case 2:
                    return "Schedule";
                case 3:
                    return "News";
                default:
                    return "Section " + (position + 1);
            }
        }
    }

    public void switchContent(Fragment fragment) {
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.main_pager, fragment)
                .commit();
        getSlidingMenu().showContent();
    }
}

我处理滑动菜单项的MenuListFragment代码: package com.giacngumo.SMS_Call_Calendar_Tracking;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.giacngumo.SMS_CallLog_Calendar_Tracking.SMS_CallLog_Calendar_Tracking.R;

public class MenuListFragment extends ListFragment {

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.list, null);
    }

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        MenuListAdapter adapter = new MenuListAdapter(getActivity());

        adapter.add(new MenuListRowItem("Backup into Calendar", R.drawable.ic_calendar));
        adapter.add(new MenuListRowItem("Backup into Gmail", R.drawable.ic_action_mail));
        adapter.add(new MenuListRowItem("Auto Sync", android.R.drawable.ic_popup_sync));
        adapter.add(new MenuListRowItem("Advanced Filter", R.drawable.filter_data_48));
        adapter.add(new MenuListRowItem("Advanced Setting", R.drawable.schedule_icon));
        adapter.add(new MenuListRowItem("Restore", R.drawable.ic_restore));
        adapter.add(new MenuListRowItem("Tutorial", R.drawable.ic_launcher));

        setListAdapter(adapter);
    }

    private class MenuListRowItem {
        public String tag;
        public int iconRes;
        public MenuListRowItem(String tag, int iconRes) {
            this.tag = tag; 
            this.iconRes = iconRes;
        }
    }

    public class MenuListAdapter extends ArrayAdapter<MenuListRowItem> {

        public MenuListAdapter(Context context) {
            super(context, 0);
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.menu_row, null);
            }
            ImageView icon = (ImageView) convertView.findViewById(R.id.menu_row_icon);
            icon.setImageResource(getItem(position).iconRes);
            TextView title = (TextView) convertView.findViewById(R.id.menu_row_title);
            title.setText(getItem(position).tag);
            //icon.setBackgroundColor(Color.BLACK);
            //title.setBackgroundColor(Color.BLACK);
            title.setTextColor(Color.WHITE);

            return convertView;
        }
    }
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        //l.setItemChecked(position, !mAdapter.isPositionChecked(position));
        //Toast.makeText(getActivity(), "click on "+position, Toast.LENGTH_SHORT).show();
        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        Fragment frag = null;
        switch (position) {
            case 0:
                //frag = new CalendarFragment();
                frag = new ColorFragment(R.color.green);
                break;

            case 1:
                //frag = new FormFragment();
                break;

            case 2:
                //frag = new CompFragment();
                break;
            case 3:
                //frag = new CompFragment();
                break;
            case 4:
                //frag = new CompFragment();
                break;
            case 5:
                //frag = new CompFragment();
                break;
            case 6:
                //frag = new CompFragment();
                break;
            default:
                //frag = new ContactFragment();
                break;
        }
        if (frag != null)
            switchFragment(frag);
    }
    // the meat of switching the above fragment
    private void switchFragment(Fragment fragment) {
        if (getActivity() == null)
            return;

        if (getActivity() instanceof MainActivity) {
            MainActivity mainActivity = (MainActivity) getActivity();
            mainActivity.switchContent(fragment);
        }/* else if (getActivity() instanceof ResponsiveUIActivity) {
            ResponsiveUIActivity ra = (ResponsiveUIActivity) getActivity();
            ra.switchContent(fragment);
        }*/
    }
}

1 个答案:

答案 0 :(得分:-2)

使用:

MainActivity.mViewPager.setCurrentItem(0);