【问题标题】:Android DrawerLayout with ExpandableListView prob with ChildClickListenerAndroid DrawerLayout with ExpandableListView prob with ChildClickListener
【发布时间】:2014-10-09 12:11:06
【问题描述】:

我正在为 DrawerLayout 菜单和子菜单使用以下代码。有些菜单没有子菜单。对于他们我想捕捉菜单点击动作,否则我想捕捉子菜单点击动作。

activity_dashboard.xml

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

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        android:background="#E6E6E6"
        android:orientation="horizontal" >
   ...................
   </RelativeLayout>

    <ExpandableListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#E6E6E6"
        android:choiceMode="singleChoice"
        android:divider="@android:color/white"
        android:dividerHeight="1dp" />

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

DashboardActivity.java

public class DashboardActivity extends ActionBarActivity {

  .......
  .........

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

        // /////////////////////// naviation menu ////////////////////////////

        mMenuItemTitles = getResources().getStringArray(R.array.menuitem_array);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ExpandableListView) findViewById(R.id.left_drawer);

        Log.d("Memu Item no.", "" + mMenuItemTitles.length);

        // 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
        /*
         * mDrawerList.setAdapter(new ArrayAdapter<String>(this,
         * R.layout.drawer_list_item, mMenuItemTitles));
         */

        mDrawerList.setAdapter(new NavigationMenuAdapter(this, getMenuItems(),
                getSubmenuItems()));

        mDrawerList.setOnGroupClickListener(new DrawerGrpClickListener());
        mDrawerList.setOnChildClickListener(new DrawerChildClickListener());

        // enable ActionBar app icon to behave as action to toggle nav drawer
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
        mDrawerLayout, /* DrawerLayout object */
        R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
        R.string.drawer_open, /* "open drawer" description for accessibility */
        R.string.drawer_close /* "close drawer" description for accessibility */
        ) {
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                invalidateOptionsMenu(); // creates call to
                                            // onPrepareOptionsMenu()
            }

            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                invalidateOptionsMenu(); // creates call to
                                            // onPrepareOptionsMenu()
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            selectItem(0);
        }

        // /////////////////////////////////////////////////////////////////
       ...................
       ................
  }

  private ArrayList<String> getMenuItems() {
        ArrayList<String> groupItem = new ArrayList<String>();
        groupItem.add("CONTENT");
        groupItem.add("BAZZAR");
        groupItem.add("PERFORMANCE");
        groupItem.add("PROGRESS");
        groupItem.add("ASSIGNMENT");
        return groupItem;
    }

  private ArrayList<Object> getSubmenuItems() {
        // TODO Auto-generated method stub

        ArrayList<Object> childItem = new ArrayList<Object>();

        ArrayList<String> child = new ArrayList<String>();
        child.add("Physics");
        child.add("Chemistry");
        child.add("Mathematics");
        child.add("Geography");
        child.add("History");
        child.add("English");
        childItem.add(child);

        child = new ArrayList<String>();
        child.add("Physics");
        child.add("Chemistry");
        child.add("Mathematics");
        child.add("Geography");
        child.add("History");
        child.add("English");
        childItem.add(child);

        childItem.add(null);
        childItem.add(null);

        ..........
    }

 /* The click listner for ListView in the navigation drawer */
    private class DrawerGrpClickListener implements
            ExpandableListView.OnGroupClickListener {

        @Override
        public boolean onGroupClick(ExpandableListView parent, View v,
                int groupPosition, long id) {
            // TODO Auto-generated method stub
            Log.d("Go to action(Grp)", "" + groupPosition);
            selectItem(groupPosition);
            if (groupPosition == 2) {
                return true;
            } else if (groupPosition == 3) {
                return true;
            }

            return false;
        }
    }

    private class DrawerChildClickListener implements
            ExpandableListView.OnChildClickListener {

        @Override
        public boolean onChildClick(ExpandableListView parent, View v,
                int groupPosition, int childPosition, long id) {
            // TODO Auto-generated method stub
            Log.d("Go to action(Child)", groupPosition + "/" + childPosition);
            if (groupPosition == 0) {
                Intent launchIntent = new Intent(DashboardActivity.this,
                        ContentActivity.class);
                launchIntent.putExtra("subjectID", childPosition);
                startActivity(launchIntent);
                return true;
            } else if (groupPosition == 1) {
                return true;
            } else if (groupPosition == 4) {
                return true;
            }
            return true;
        }
    }

    private void selectItem(int position) {
        // update the main content by replacing fragments

        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        // mDrawerLayout.closeDrawer(mDrawerList);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.dashboard, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.

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

        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}

NavigationMenuAdapter.java

public class NavigationMenuAdapter extends BaseExpandableListAdapter {

    public ArrayList<String> groupItem, tempChild;
    public ArrayList<Object> childtem = new ArrayList<Object>();
    public LayoutInflater minflater;
    public Activity activity;
    private final Context context;
    private LayoutInflater mInflater;

    public NavigationMenuAdapter(Context context, ArrayList<String> grList,
            ArrayList<Object> childItem) {
        this.context = context;
        mInflater = LayoutInflater.from(context);
        groupItem = grList;
        this.childtem = childItem;
    }

    public void setInflater(LayoutInflater mInflater, Activity act) {
        this.minflater = mInflater;
        activity = act;
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return null;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return 0;
    }

    @Override
    public View getChildView(int groupPosition, final int childPosition,
            boolean isLastChild, View convertView, ViewGroup parent) {
        tempChild = (ArrayList<String>) childtem.get(groupPosition);

        ViewHolder holder;
        if (convertView == null) {

            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.drawer_list_item_child,
                    null);
            holder.menuTextView = (TextView) convertView
                    .findViewById(R.id.menuTextView);

            convertView.setTag(holder);
        } else
            holder = (ViewHolder) convertView.getTag();

        holder.menuTextView.setText(tempChild.get(childPosition));
        return convertView;

    }

    @Override
    public int getChildrenCount(int groupPosition) {
        if (((ArrayList<String>) childtem.get(groupPosition)) == null)
            return 0;
        return ((ArrayList<String>) childtem.get(groupPosition)).size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return null;
    }

    @Override
    public int getGroupCount() {
        return groupItem.size();
    }

    @Override
    public void onGroupCollapsed(int groupPosition) {
        super.onGroupCollapsed(groupPosition);
    }

    @Override
    public void onGroupExpanded(int groupPosition) {
        super.onGroupExpanded(groupPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return 0;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded,
            View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {

            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.drawer_list_item, null);
            holder.menuTextView = (TextView) convertView
                    .findViewById(R.id.menuTextView);
            holder.iconImageView = (ImageView) convertView
                    .findViewById(R.id.iconImageView);
            holder.iconExpandCollapse = (ImageView) convertView
                    .findViewById(R.id.iconExpandCollapse);
            holder.itemBox = (RelativeLayout) convertView
                    .findViewById(R.id.itemBox);

            convertView.setTag(holder);
        } else
            holder = (ViewHolder) convertView.getTag();

        Log.d("getGroupView","groupPosition : " + groupPosition + "/" + "getChildrenCount : " + getChildrenCount(groupPosition));

        if (getChildrenCount(groupPosition) != 0) {
            holder.iconExpandCollapse.setVisibility(View.VISIBLE);
            if (isExpanded){
                holder.itemBox.setBackgroundColor(Color.parseColor("#B8B8B8"));
                holder.iconExpandCollapse
                        .setImageResource(R.drawable.icon_minus);
            }else{
                holder.itemBox.setBackgroundColor(Color.parseColor("#E6E6E6"));
                holder.iconExpandCollapse
                        .setImageResource(R.drawable.icon_plus);
            }
        } else
            holder.iconExpandCollapse.setVisibility(View.INVISIBLE);

        holder.menuTextView.setText(groupItem.get(groupPosition));
        return convertView;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return false;
    }

    public static class ViewHolder {
        public RelativeLayout itemBox;
        TextView menuTextView;
        ImageView iconImageView;
        ImageView iconExpandCollapse;
    }
}

以上代码可以成功捕捉到菜单点击选项,但是未能捕捉到任何子菜单点击动作。代码有什么问题?

【问题讨论】:

    标签: android expandablelistview onclicklistener drawerlayout


    【解决方案1】:

    在您的子菜单项中添加新对象而不是 null,如下所示:

    private ArrayList<Object> getSubmenuItems() {
        // TODO Auto-generated method stub
    
        ArrayList<Object> childItem = new ArrayList<Object>();
    
        ArrayList<String> child = new ArrayList<String>();
        child.add("Physics");
        child.add("Chemistry");
        child.add("Mathematics");
        child.add("Geography");
        child.add("History");
        child.add("English");
        childItem.add(child);
    
        child = new ArrayList<String>();
        child.add("Physics");
        child.add("Chemistry");
        child.add("Mathematics");
        child.add("Geography");
        child.add("History");
        child.add("English");
        childItem.add(child);
    
        childItem.add(new ArrayList<String>());
        childItem.add(new ArrayList<String>());
    
        ..........
    }
    

    【讨论】:

    • 我对这个'null'没有任何问题。它完美地显示出来。我可以完美地处理所有菜单(带有子菜单和不带子菜单)点击事件。问题出在子菜单中。 OnChildClickListener 中没有触发任何操作。
    • 在你的 NavigationMenuAdapter 中返回 true 在 isChildSelectable
    • 是的,这就是原因。我只是错过了。谢谢你,韦德
    【解决方案2】:

    你正在使用ExpandableListView,如果你想要我被点击的子菜单位置请执行以下代码。

       mDrawerList.setOnChildClickListener(new OnChildClickListener() {
    
                    @Override
                    public boolean onChildClick(ExpandableListView arg0, View arg1, int gorugPosition,
                            int childPosition, long arg4) {
    
    
                   System.out.println("submenu postion - "+childPosition)
    
                 // Do your stuff that you want.
    
    
    
                        // Insert the fragment by replacing any existing fragment
                        FragmentManager fragmentManager = getFragmentManager();
                        fragmentManager.beginTransaction()
                                       .replace(R.id.content_frame, fragment)
                                       .commit();
    
                        mDrawerList.setItemChecked(childPosition, true);
                        setTitle(title);
                        mDrawer.closeDrawers();
    
                        return false;
                    }
                });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多