使用Android支持库v23.4.0时,导航抽屉无法打开

时间:2016-05-23 07:35:09

标签: java android navigation-drawer android-support-library

大家好我正在开发一个使用旧导航抽屉方法的应用程序。当我将'com.android.support:appcompat-v7:23.1.1'更新为'com.android.support:appcompat-v7:23.4.0'我的导航抽屉未打开时。

我调试了代码并查找了已弃用的项目,但找不到任何错误代码或消息。一切都很完美,但导航抽屉没有打开。这是我的代码。提前致谢。

MainActivity.class

public class MainActivity extends AppCompatActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks, TapuInterface.IAuthorization {

    TapuUtils tapuUtils = new TapuUtils();
    String userMail, userPassword;
    SharedPreferences.Editor editor;
    SharedPreferences preferences;
    Tracker mTracker;
    Bundle bundle;
    String tapuAuth = "false";

    private NavigationDrawerFragment mNavigationDrawerFragment;

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

        GoogleAnalytics.getInstance(this).setLocalDispatchPeriod(15);

        AnalyticsApplication application = (AnalyticsApplication) getApplication();
        mTracker = application.getDefaultTracker();

        Countly.sharedInstance().init(this, getString(R.string.countly_server), getString(R.string.countly_key));

        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);


        mNavigationDrawerFragment.setUp(R.id.navigation_drawer,(DrawerLayout) findViewById(R.id.drawer_layout));
        ActionBar mActionBar = getSupportActionBar();
        assert mActionBar != null;
        mActionBar.setBackgroundDrawable(new ColorDrawable(0xFF297AA6));

        if (savedInstanceState == null) {
            bundle = getIntent().getExtras();
            userMail = bundle.getString("personname");
            userPassword = bundle.getString("personpassword");
            tapuAuth = bundle.getString("tapu");
        }

        TapuCredentials.setUserMail(userMail);
        TapuCredentials.setUserPassword(userPassword);
        TapuCredentials.setTapuAuth(tapuAuth);

    }

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.container, MainMapFragment.newInstance(position + 1), "MapFragment")
                .commit();
    }




    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            getMenuInflater().inflate(R.menu.main, menu);

            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(this)
                .setMessage(getString(R.string.exit_alert))
                .setCancelable(true)
                .setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        MainActivity.this.finish();
                        LoginActivity.fa.finish();

                    }
                })
                .setNegativeButton(getString(R.string.no), null)
                .show();
    }


    @Override
    public void onStart() {
        super.onStart();
        Countly.sharedInstance().onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
        Countly.sharedInstance().onStop();

    }

    @Override
    protected void onResume() {
        super.onResume();

        mTracker.setScreenName(getResources().getString(R.string.main_screen));
        mTracker.send(new HitBuilders.ScreenViewBuilder().build());

    }


}

这是我的NavigationDrawer.class

public class NavigationDrawerFragment extends Fragment {
    private static NavigationDrawerAdapter myAdapter;
    public static ArrayList<ListItem> myItems = new ArrayList<>();
    public static UserCredentials mUserCredentials = new UserCredentials();
    private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
    private NavigationDrawerCallbacks mCallbacks;
    private android.support.v7.app.ActionBarDrawerToggle mDrawerToggle;
    private DrawerLayout mDrawerLayout;
    private DynamicListView mDrawerListView;
    private View mFragmentContainerView;
    private int mCurrentSelectedPosition = 0;
    static LegendFragment frLegend = new LegendFragment();
    Button mEditLayers, mShowLegend;
    String personName,userType,tapucontrol;
    TextView mLayersText;
    static FragmentManager fragmentManager;
    Bundle extras;

    public NavigationDrawerFragment() {

    }

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



    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(true);
        mDrawerLayout.setScrimColor(getResources().getColor(android.R.color.transparent));


    }

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

        View rootView = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);

        if (savedInstanceState == null) {
            extras = getActivity().getIntent().getExtras();
            if(mUserCredentials.getUserName()==null || mUserCredentials.getPassword()==null){
                mUserCredentials.setUserAccount(extras.getString("username"), extras.getString("password"));
            }
            personName = extras.getString("personname");
            userType = extras.getString("usertype");
            tapucontrol = extras.getString("tapu");
        }


        mDrawerListView = (DynamicListView) rootView.findViewById(R.id.dynamiclistivew);
        mLayersText = (TextView) rootView.findViewById(R.id.textview_layers);
        myAdapter = new NavigationDrawerAdapter(getActivity(), myItems);
        mDrawerListView.setAdapter(myAdapter);

        fragmentManager = getFragmentManager();
        mDrawerListView.setCheeseList(myItems);
        mDrawerListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

        mEditLayers = (Button) rootView.findViewById(R.id.button);
        mShowLegend = (Button) rootView.findViewById(R.id.legendbutton);
        mEditLayers.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                if (mEditLayers.getText().equals("Düzenle")) {
                    myAdapter.setEditMode(true);
                    mEditLayers.setText(getActivity().getString(R.string.ok));


                } else {
                    myAdapter.setEditMode(false);
                    mEditLayers.setText(getActivity().getString(R.string.editlayers));


                }
            }
        });


        return rootView;

    }

    public boolean isDrawerOpen() {
        return mDrawerLayout != null && mDrawerLayout.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) {
        mFragmentContainerView = getActivity().findViewById(fragmentId);
        mDrawerLayout = drawerLayout;

        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        // set up the drawer's list view with items and click listener
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);

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

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the navigation drawer and the action bar app icon.
        mDrawerToggle = new android.support.v7.app.ActionBarDrawerToggle(
                getActivity(),                    /* host Activity */
                mDrawerLayout,                    /* DrawerLayout object */
                null,             /* 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);


            }
        };


        // Defer code dependent on restoration of previous instance state.
        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);
        FragmentTransaction ft = fragmentManager.beginTransaction();
        if (frLegend.isAdded()) {
            ft.remove(frLegend);
            ft.commitAllowingStateLoss();
            mEditLayers.setVisibility(View.VISIBLE);
            mLayersText.setText("Katmanlar");
        }


    }

    @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 the drawer is open, show the global app actions in the action bar. See also
        // showGlobalContextActionBar, which controls the top-left area of the action bar.
        if (mDrawerLayout != null && isDrawerOpen()) {
            inflater.inflate(R.menu.main, menu);
           // showGlobalContextActionBar();
        }
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        switch (item.getItemId()) {
            case R.id.action_search:
                Intent s = new Intent(getActivity(), SearchMainActivity.class);
                s.putExtra("username", mUserCredentials.getUserName());
                s.putExtra("password", mUserCredentials.getPassword());
                s.putExtra("tapu",tapucontrol);
                startActivity(s);
                break;
            case R.id.action_basemaps:
                Intent cb = new Intent(getActivity(), BaseMapsActivity.class);
                startActivity(cb);
                break;
            case R.id.action_addlayer:
                if (isNetworkAvailable(getActivity())) {
                    Intent al = new Intent(getActivity(), AddLayerActivity.class);
                    al.putExtra("usertype", userType);
                    startActivity(al);
                } else {
                    Toast.makeText(getActivity(), "Lütfen internet bağlantınızı kontrol ediniz.", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.action_about:
                Intent au = new Intent(getActivity(), AboutActivity.class);
                au.putExtras(extras);
                startActivity(au);
                break;
        }


        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(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);

    }

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

    /**
     * Callbacks interface that all activities using this fragment must implement.
     */
    public interface NavigationDrawerCallbacks {
        /**
         * Called when an item in the navigation drawer is selected.
         */
        void onNavigationDrawerItemSelected(int position);
    }

    public class ListItem {
        String textdata;
        Integer progress;

        public ListItem(String textdata, int progress) {
            this.textdata = textdata;
            this.progress = progress;
        }

        public boolean equals(Object o) {
            ListItem ndListItemObject = (ListItem) o;
            return this.textdata.equalsIgnoreCase(ndListItemObject.textdata);
        }

    }


    public void addLayersection(String name, int progress) {
        ListItem listItem = new ListItem(name, progress);

        if (myItems.size() == 0) {
            myItems.add(0, listItem);

        } else {
            if (myItems.size() == 0) {
                myItems.add(0, listItem);
            } else {

                if (myItems.contains(listItem)) {
                    myItems.remove(listItem);
                } else {
                    myItems.add(0, listItem);


                }
            }
        }

        myAdapter.notifyDataSetChanged();

    }

    public int getListSizee() {
        return myItems.size();
    }

    public static boolean isNetworkAvailable(Context context) {
        return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
    }

2 个答案:

答案 0 :(得分:0)

抽屉被锁定。

更改

<?php
    $args = array( 'numberposts' => '1', 'offset' => '0', 'orderby' => 'post_date', 'order' => 'DESC', 'post_status' => 'publish' );
    $recent_posts = wp_get_recent_posts( $args );
    $home = home_url( '/' );
    $homeURL = esc_url( $home );
    $before = '<a href="';
    $after = '">dive in</a>';

    foreach( $recent_posts as $recent ){

        $slug = basename( get_permalink($recent["ID"]) );

        // if post is audio
        if ( has_category('audioz', $recent["ID"]) ) {
            echo $before . $homeURL . "audio/" . "#" . $slug . $after;
        }
        // else if post is video
        else if ( has_category('videoz', $recent["ID"]) ) {
            echo $before . $homeURL . "videos/" . "#" . $slug . $after;
        }
        // else if post is article
        else if ( has_category('articlez', $recent["ID"]) ) {
            echo $before . $homeURL . "article/" . "#" . $slug . $after;
        }
        // else if post is zazzle link
        else if ( has_category('zazzle', $recent["ID"]) ) {
            echo $before . $homeURL . "store/" . "#" . $slug . $after;
        } 
    }
?>

mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);

答案 1 :(得分:0)

这是我自己找到的最新解决方案。 drawerOpenCloseControl是布尔标志。我控制的是真还是假。然后手动打开和关闭。

@Override
public boolean onOptionsItemSelected(MenuItem item) {    
    switch (item.getItemId()) {
          case android.R.id.home:
            if(drawerOpenCloseControl){
                mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN);
                drawerOpenCloseControl = false;
            }
            else{
                mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                drawerOpenCloseControl = true;
            }
            break;

    }
    return super.onOptionsItemSelected(item);
}