显示或隐藏片段菜单

时间:2015-07-25 18:39:47

标签: java android android-fragments android-fragmentactivity

我正在尝试创建一个包含三个不同片段的活动作为菜单。

用户应该根据活动的某些数据只看到他需要的片段。

这是我的主要XML文件:

<RelativeLayout 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"
    android:id="@+id/MainScreenLayout"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="ibuy.ibuy.MainScreen">

    <android.support.v4.widget.DrawerLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="ibuy.ibuy.MainScreen">

        .
        .
        .

        <fragment
            android:id="@+id/navigation_drawer1"
            android:layout_width="@dimen/navigation_drawer_width"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:name="Menus.ManagerMainMenu"
            tools:layout="@layout/fragment_navigation_drawer"
            android:alpha="255"/>

        <fragment
            android:id="@+id/navigation_drawer2"
            android:layout_width="@dimen/navigation_drawer_width"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:name="Menus.MainConnectedMenu"
            tools:layout="@layout/fragment_navigation_drawer"
            android:alpha="255"/>

        <fragment
            android:id="@+id/navigation_drawer3"
            android:layout_width="@dimen/navigation_drawer_width"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:name="Menus.MainDisConnectedMenu"
            tools:layout="@layout/fragment_navigation_drawer"
            android:alpha="255"/>

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

</RelativeLayout>

这是我的主要Java文件:

public class MainScreen extends ActionBarActivity implements ManagerMainMenu.NavigationDrawerCallbacks,MainConnectedMenu.NavigationDrawerCallbacks,MainDisConnectedMenu.NavigationDrawerCallbacks {

    .
    .
    .
    private ManagerMainMenu mnMenu = new ManagerMainMenu();
    private MainConnectedMenu conMenu = new MainConnectedMenu();
    private MainDisConnectedMenu disMenu = new MainDisConnectedMenu();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main_screen);
        Bundle extras = getIntent().getExtras();
        .
        .
        .

        mnMenu = (ManagerMainMenu) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer1);

        mnMenu.setUp(R.id.navigation_drawer1, (DrawerLayout) findViewById(R.id.drawer_layout));

        conMenu = (MainConnectedMenu) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer2);

        conMenu.setUp(R.id.navigation_drawer2, (DrawerLayout) findViewById(R.id.drawer_layout));

        disMenu = (MainDisConnectedMenu) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer3);

        disMenu.setUp(R.id.navigation_drawer3, (DrawerLayout) findViewById(R.id.drawer_layout));

        android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

    if (storeID > 0) {
            ft.show(mnMenu);
            ft.hide(conMenu);
            ft.hide(disMenu);
        } else if (userID > 0) {
            ft.hide(mnMenu);
            ft.show(conMenu);
            ft.hide(disMenu);
        } else {
            ft.hide(mnMenu);
            ft.hide(conMenu);
            ft.show(disMenu);
        }
        ft.commit();
    }

    public void onNavigationDrawerItemSelected(int position) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.MainScreenLayout, new PlaceholderFragment()).commit();
        .
        .
        .

    }

    .
    .
    .
}

这三个片段与其项目列表数组相同。

这是片段Java文件中的一个:

public class ManagerMainMenu extends Fragment {

    private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
    private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
    private NavigationDrawerCallbacks mCallbacks;
    private ActionBarDrawerToggle mDrawerToggle;
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerListView;
    private View mFragmentContainerView;
    private int mCurrentSelectedPosition = 0;
    private boolean mFromSavedInstanceState;
    private boolean mUserLearnedDrawer;

    public ManagerMainMenu() {    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
        mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);

        if (savedInstanceState != null) {
            mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
            mFromSavedInstanceState = true;
        }

        selectItem(mCurrentSelectedPosition);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mDrawerListView = (ListView) inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
        mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectItem(position);
            }
        });
        mDrawerListView.setAdapter(new ArrayAdapter<String>(
                getActionBar().getThemedContext(),
                android.R.layout.simple_list_item_activated_1,
                android.R.id.text1,
                new String[]{"Store Rank", "Store Details", "Sales", "Add Item",
                        "Update Store Details", "Personal Details", "LogOut"}));
        mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
        return mDrawerListView;
    }

    public boolean isDrawerOpen() {
        return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
    }

    public void setUp(int fragmentId, DrawerLayout drawerLayout) {
        mFragmentContainerView = getActivity().findViewById(fragmentId);
        mDrawerLayout = drawerLayout;

        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(
                getActivity(),                    /* host Activity */
                mDrawerLayout,                    /* DrawerLayout object */
                R.drawable.ic_drawer,             /* nav drawer image to replace 'Up' caret */
                R.string.navigation_drawer_open,  /* "open drawer" description for accessibility */
                R.string.navigation_drawer_close  /* "close drawer" description for accessibility */
        ) {
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                if (!isAdded()) {
                    return;
                }

                getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                if (!isAdded()) {
                    return;
                }

                if (!mUserLearnedDrawer) {
                    mUserLearnedDrawer = true;
                    SharedPreferences sp = PreferenceManager
                            .getDefaultSharedPreferences(getActivity());
                    sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
                }

                getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }
        };

        if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
            mDrawerLayout.openDrawer(mFragmentContainerView);
        }

        mDrawerLayout.post(new Runnable() {
            @Override
            public void run() {
                mDrawerToggle.syncState();
            }
        });

        mDrawerLayout.setDrawerListener(mDrawerToggle);
    }

    private void selectItem(int position) {
        mCurrentSelectedPosition = position;
        if (mDrawerListView != null) {
            mDrawerListView.setItemChecked(position, true);
        }
        if (mDrawerLayout != null) {
            mDrawerLayout.closeDrawer(mFragmentContainerView);
        }
        if (mCallbacks != null) {
            mCallbacks.onNavigationDrawerItemSelected(position);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mCallbacks = (NavigationDrawerCallbacks) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mCallbacks = null;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Forward the new configuration the drawer toggle component.
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    private ActionBar getActionBar() {
        return ((ActionBarActivity) getActivity()).getSupportActionBar();
    }

    public static interface NavigationDrawerCallbacks {
        void onNavigationDrawerItemSelected(int position);
    }
}

我尝试使用setMenuVisibility()和setUserVisibleHint(),但它没有任何影响力。之后我尝试将FragmentTransaction与show和hide一起使用,它也没有做任何事情。

如何隐藏其中两个片段并显示第三个片段?

提前谢谢你!

1 个答案:

答案 0 :(得分:0)

我认为这可以解决您的问题。

FragmentTransaction ft = getFragmentManager().beginTransaction();

if (storeID > 0) {
    ft.show(mnMenu);
    ft.hide(conMenu);
    ft.hide(disMenu);
} else if (userID > 0) {
        ...
}

等等..