onClick Listener on DrawerLayout Does Not Launch Toast

前端 未结 1 1071
南旧
南旧 2021-01-27 02:58

I\'m attempting to implement a toast depending on the item clicked in a DrawerLayout - however I cannot seem to get the toasts to appear no matter what I do. I\'m not sure exact

相关标签:
1条回答
  • 2021-01-27 03:38

    I recently did something very much like this. I was using Fragments but the concept is very much the same.

    First I created the DrawerLayout:

        @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);
    
    // read in the menu items form the string array
        String[] menuList = getResources().getStringArray(R.array.drawer_menu);
        mDrawerList.setAdapter(new ArrayAdapter<String>(this,  R.layout.drawer_list_item, menuList));
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
    

    Then I define the DrawerItemClickListener:

    /* The click listener for ListView in the navigation drawer */
    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    }
    

    Finally I implement the selectItem method:

        private void selectItem(int position) {
        // update the main content by replacing fragments
        Fragment fragment;
    
        if ( position == 1 )
        {
            fragment = new CalendarFrag();
        }
        else if ( position == 2 )
        {
            fragment = new ContactsFrag();
        }
        else
        {
            fragment = new EmailListFragment();
        }
    
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
    
        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        mDrawerLayout.closeDrawer(mDrawerList);
    }
    

    You could easily replace the Fragments with Activities, and the beginTransation with a startActivity.

    0 讨论(0)
提交回复
热议问题