活动可点击下方的右侧导航抽屉

时间:2014-09-03 15:52:45

标签: android android-fragments navigation navigation-drawer

我有一个带有2个导航抽屉的活动:一个在左侧,“自定义”导航抽屉带有菜单列表,另一个在右侧带有一些搜索过滤器。此活动还包含一个列表片段,当我单击一个元素时,将打开一个新活动。

当我打开左侧抽屉时,我的活动被禁用,我无法点击片段的任何元素。

另一方面,当我打开右侧抽屉时,我仍然能够滚动并通过抽屉单击片段的元素。

Main动作中,我只设置了抽屉。 在List片段中,我不处理抽屉。 NavigationDrawer是Android Studio自动生成的导航抽屉。 这是我的右侧抽屉:

package it.gn.sfa;


import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import it.gn.sfa.adapter.MenuListAdapter;
import it.gn.sfa.db.SfaDbHelper;
import it.gn.sfa.db.datatype.MenuInput;
import it.gn.sfa.helper.PreferenceHelper;
import it.gn.sfa.service.GetMenuService;
import it.gn.sfa.utilities.Constants;
import it.gn.sfa.utilities.Utilities;

/**
 * Fragment used for managing interactions for and presentation of a navigation drawer.
 * See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
 * design guidelines</a> for a complete explanation of the behaviors implemented here.
 */
public class FilterDrawerFragment extends Fragment {

    /**
     * Remember the position of the selected item.
     */
    private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";

    /**
     * Per the design guidelines, you should show the drawer on launch until the user manually
     * expands it. This shared preference tracks this.
     */
    private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";

    /**
     * A pointer to the current callbacks instance (the Activity).
     */
    private FilterDrawerCallbacks mCallbacks;

    /**
     * Helper component that ties the action bar to the navigation drawer.
     */
    private ActionBarDrawerToggle mDrawerToggle;

    private DrawerLayout mFilterDrawerLayout;
    //private ListView mDrawerListView;
    private View mDrawerListView;
    private View mFragmentContainerView;
    private int mCurrentSelectedPosition;
    private boolean mFromSavedInstanceState;
    private boolean mUserLearnedDrawer;

    private SfaDbHelper sfaDb;

    // Menu
    private Intent getMenuIntent;
    //private BroadcastReceiver getMenu;
    private IntentFilter getMenuFilter;
    private List<MenuInput> menuInput;
    private MenuListAdapter mMenuAdapter;
    private Menu _menu;

    private Spinner remaindersSpinner;
    private Spinner typeSpinner;
    private TextView lastOrderFromText;
    private TextView lastOrderToText;
    private Spinner channelSpinner;

    private String remainders;
    private String type;
    private String lastOrderFrom;
    private String lastOrderTo;
    private String channel;

    // public void setSelection(int position) {mDrawerListView.setItemChecked(position,true);    }


    public FilterDrawerFragment() {
    }

    private void initDb() {
        sfaDb = SfaDbHelper.getInstance(getActivity().getApplication());
        if (!sfaDb.isOpen()) {
            sfaDb.open();
        }
        sfaDb.pushCount();
    }

    private void initFragment() {
        getMenuFilter = new IntentFilter();
        getMenuFilter.addAction(Constants.MENU);

        /*getMenu = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                //Log.i("Main", "GET MENU");
                //initMenu();
                mDrawerListView.setAdapter(mMenuAdapter);
                mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
            }
        };
        getActivity().registerReceiver(getMenu, getMenuFilter);*/
        //mDrawerListView.setChoiceMode(1);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        // Read in the flag indicating whether or not the user has demonstrated awareness of the
        // drawer. See PREF_USER_LEARNED_DRAWER for details.
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
        mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);

        //TODO: controllare perché se ho come menu preferito IMPOSTAZIONI, mi carica impostazioni ma non mi permette di tornare indietro
        //mCurrentSelectedPosition = Integer.parseInt(PreferenceHelper.getPreferredMenu(getActivity().getApplicationContext())) - 7;
        if (savedInstanceState != null) {
            mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
            mFromSavedInstanceState = true;
        }

        initDb();
        // Select either the default item (0) or the last selected item.
        //selectItem(mCurrentSelectedPosition);

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Indicate that this fragment would like to influence the set of actions in the action bar.
        setHasOptionsMenu(true);
    }

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

        mDrawerListView = inflater.inflate(R.layout.fragment_filter_drawer, container, false).getRootView();

        return mDrawerListView;

    }

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

    /**
     * Users of this fragment must call this method to set up the navigation drawer interactions.
     *
     * @param fragmentId   The android:id of this fragment in its activity's layout.
     * @param drawerLayout The DrawerLayout containing this fragment's UI.
     */
    public void setUp(int fragmentId, DrawerLayout drawerLayout) {


        initFragment();
        if (getActivity().getIntent().getBooleanExtra("syncMenu", false)) {
            getMenuIntent = new Intent(getActivity(), GetMenuService.class);
            getMenuIntent.putExtra("username", PreferenceHelper.getUser(getActivity().getApplicationContext()));
            getActivity().startService(getMenuIntent);
        }
        mFragmentContainerView = getActivity().findViewById(fragmentId);
        mFilterDrawerLayout = drawerLayout;

        // set a custom shadow that overlays the main content when the drawer opens
        mFilterDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

        // lock border swipe - !! use same layout as navDraw
        mFilterDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, mFragmentContainerView);

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the navigation drawer and the action bar app icon.
        mDrawerToggle = new ActionBarDrawerToggle(
                getActivity(),                    /* host Activity */
                mFilterDrawerLayout,              /* 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 (drawerView.equals(mFragmentContainerView)) {
                    Utilities.inflateNewMenu(CustomerListFragment.menuResource, getActivity());
                    ((Main) getActivity()).restoreActionBar();
                }

                if (!isAdded()) {
                    return;
                }


            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);

                if (drawerView.equals(mFragmentContainerView)) {
                    Utilities.inflateNewMenu(R.menu.customer_filter_menu, getActivity());
                    showGlobalContextActionBar();
                }

                if (!isAdded()) {
                    return;
                }

                //getActivity().invalidateOptionsMenu();

            }
        };

    }


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

    @Override
    public void onDetach() {
        //getActivity().unregisterReceiver(getMenu);
        sfaDb.popCount();
        sfaDb.close();
        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);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

        if (mFilterDrawerLayout != null && isDrawerOpen()) {
            showGlobalContextActionBar();
        }
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            case R.id.filter_accept:
                Map<String, String> filters = new HashMap<String, String>();

                remaindersSpinner = (Spinner) mFilterDrawerLayout.findViewById(R.id.customer_filter_remainders);
                typeSpinner = (Spinner) mFilterDrawerLayout.findViewById(R.id.customer_filter_type);
                lastOrderFromText = (TextView) mFilterDrawerLayout.findViewById(R.id.customer_filter_last_order_from);
                lastOrderToText = (TextView) mFilterDrawerLayout.findViewById(R.id.customer_filter_last_order_to);
                channelSpinner = (Spinner) mFilterDrawerLayout.findViewById(R.id.customer_filter_channel);

                remainders = remaindersSpinner.getSelectedItem().toString();
                type = typeSpinner.getSelectedItem().toString();
                lastOrderFrom = lastOrderFromText.getText().toString();
                lastOrderTo = lastOrderToText.getText().toString();
                channel = channelSpinner.getSelectedItem().toString();

                filters.put("remainders", remainders);
                filters.put("type", type);
                filters.put("lastOrderFrom", lastOrderFrom);
                filters.put("lastOrderTo", lastOrderTo);
                filters.put("channel", channel);

                //aggiunge alla callback i filtri inseriti
                mCallbacks.onFilterDrawerCheckSelected(filters);

                mFilterDrawerLayout.closeDrawers();
                restoreCustomerListMenu();
                break;

            case android.R.id.home:
                if(mFilterDrawerLayout.isDrawerOpen(mFragmentContainerView)){
                    mFilterDrawerLayout.closeDrawers();
                    emptyFiltersViews();
                    restoreCustomerListMenu();
                }
                break;

        }

        /*
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        if (item.getItemId() == R.id.action_example) {
            Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
            return true;
        }

*/
        return super.onOptionsItemSelected(item);
    }

    /**
     * Per the navigation drawer design guidelines, updates the action bar to show the global app
     * 'context', rather than just what's in the current screen.
     */
    private void showGlobalContextActionBar() {
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setTitle(R.string.app_name);
    }

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

    /**
     * Callbacks interface that all activities using this fragment must implement.
     */
    public static interface FilterDrawerCallbacks {
        /**
         * Called when an item in the navigation drawer is selected.
         */
        void onFilterDrawerCheckSelected(Map<String, String> filters);
    }

    private void restoreCustomerListMenu(){
        ActionBar actionBar = getActivity().getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);
        actionBar.setDisplayShowTitleEnabled(true);
        ((Main) getActivity()).restoreActionBar();
        Utilities.inflateNewMenu(R.menu.customer_list_menu, getActivity());
        ((Main)getActivity()).setUpSearchBarOnMenu();
    }

    private void emptyFiltersViews(){
        remaindersSpinner = (Spinner) mFilterDrawerLayout.findViewById(R.id.customer_filter_remainders);
        typeSpinner = (Spinner) mFilterDrawerLayout.findViewById(R.id.customer_filter_type);
        lastOrderFromText = (TextView) mFilterDrawerLayout.findViewById(R.id.customer_filter_last_order_from);
        lastOrderToText = (TextView) mFilterDrawerLayout.findViewById(R.id.customer_filter_last_order_to);
        channelSpinner = (Spinner) mFilterDrawerLayout.findViewById(R.id.customer_filter_channel);

        remaindersSpinner.setSelection(0);
        typeSpinner.setSelection(0);
        channelSpinner.setSelection(0);
        lastOrderFromText.setText("");
        lastOrderToText.setText("");

    }

}

它与左侧的NavigationDrawer非常相似,它们也使用相同的drawerLayout。

为什么左侧抽屉“禁用”活动而右侧没有?

0 个答案:

没有答案