2014-02-12 6 views
0

Я пытаюсь сделать ListView со следующей структурой:Expandandable ListView с дочерними элементами в корне

Listview 
    -> child 
    -> child 
    -> group 
      -> child 
      -> child 
    -> child 

Как бы я идти о этом из палочки?

Должен ли я получить группу, чтобы действовать, как ребенок, или это возможно сделать это правильно вот так:

У меня есть объект MenuRow

public class MenuRow { 
public String title; 

public MenuRow(String title) { 
    this.title = title; 
} 

} 

то я имею MenuGroup и MenuChild которые проходят MenuRow, это позволяет мне сделать следующее:

ArrayList<MenuRow> menu = new ArrayList<MenuRow>(); 
    menu.add(new MenuChild("row 1")); 
    menu.add(new MenuChild("row 2")); 
    MenuGroup group = new MenuGroup("group"); 
    MenuChild groupChild = new MenuChild("group child"); 
    group.items.add(groupChild); 
    menu.add(group); 

Я не могу понять, как я должен идти о моем Промишленое в адаптере.

@Override 
    public Object getChild(int groupPosition, int childPosition) { 
     MenuRow row = menu.get(groupPosition); 
     if (row instanceof MenuGroup) { 
      ArrayList<MenuChild> chList = ((MenuGroup) row).getItems(); 
     } 
     else{ 
       return null; 
     } 

     return chList; 
    } 

Этот метод, к примеру, не подходит для моего решения. Как я должен пытаться достичь своей цели? мне нужно использовать другой адаптер? (Мой текущий один продлить BaseExpandableListAdapter)

ответ

1

Я уже работал с такой проблемой, и вот такой подход я использовал:

И создали объект класса, который будет использоваться в качестве пункта меню слева для детей и видом родительских

public class LeftMenuItem { 

    int mTextId; 
    int mImageId; 
    //Action to be taken after clicking on the item 
    String mAction; 

    public LeftMenuItem(int textId, int imageId,String action) { 
     this.mTextId = textId; 
     this.mImageId = imageId; 
     this.mAction = action; 
    } 

    public int getTextId() { 
     return mTextId; 
    } 

    public void setTextId(int textId) { 
     this.mTextId = textId; 
    } 

    public int getImageId() { 
     return mImageId; 
    } 

    public void setImageId(int imageId) { 
     this.mImageId = imageId; 
    } 

    public String getAction() { 
     return mAction; 
    } 

    public void setAction(String action) { 
     this.mAction = action; 
    } 

} 

и создал свой расширяемый элемент списка, который будет содержать leftmenuitem родителя и ArrayList детей, если найдены

public class ExpandableLeftMenuItem { 

    LeftMenuItem mParentItem; 
    ArrayList<LeftMenuItem> mChildItems; 

    public ExpandableLeftMenuItem(LeftMenuItem parentItem, 
      ArrayList<LeftMenuItem> childItems) { 
     this.mParentItem = parentItem; 
     this.mChildItems = childItems; 
    } 

    public LeftMenuItem getParentItem() { 
     return mParentItem; 
    } 

    public void setParentItem(LeftMenuItem parentItem) { 
     this.mParentItem = parentItem; 
    } 

    public ArrayList<LeftMenuItem> getChildItems() { 
     return mChildItems; 
    } 

    public void setChildItems(ArrayList<LeftMenuItem> childItems) { 
     this.mChildItems = childItems; 
    } 

} 

Затем я обрабатываюсь ExpandableListView onChildClickListener и onGroupClickListener следующего

// In Case of clicking on an item that has children, then get the action 
     // of this child item and show the screen with this action 
     mLeftMenu.setOnChildClickListener(new OnChildClickListener() { 
      @Override 
      public boolean onChildClick(ExpandableListView parent, View view, int groupPosition, int childPosition, long id) { 
       if (!mLeftMenuItems.get(groupPosition).getChildItems().isEmpty()) { 

        String action = ((LeftMenuItem) mLeftMenuItems.get(groupPosition).getChildItems().get(childPosition)).getAction(); 
        setSelectedSection(action); 
        handleLeftMenuClick(action); 

        return true; 
       } 
       return false; 
      } 
     }); 
     // In Case of clicking on an item that has no children, then get the 
     // action of this item and show the screen with this action 
     mLeftMenu.setOnGroupClickListener(new OnGroupClickListener() { 

      @Override 
      public boolean onGroupClick(ExpandableListView parent, View view, int groupPosition, long id) { 
       if (mLeftMenuItems.get(groupPosition).getChildItems().isEmpty()) { 
        String action = ((LeftMenuItem) mLeftMenuItems.get(groupPosition).getParentItem()).getAction(); 
        setSelectedSection(action); 
        handleLeftMenuClick(action); 
// Return true to stop parent from expanding or collapsing group 
        return true; 
       } 
// Return true to handle click as parent by expanding or collapsing group 
        return false; 
      } 
     }); 

Тогда для следующего

ExpandableListView: 
    group 
    group 
    group 
      child 
      child 
    group 
      child 
      child 

Вы создадите следующие пункты меню:

ArrayList<ExpandableLeftMenuItem> mMenuItems = new ArrayList<ExpandableLeftMenuItem>(); 
mMenuItems.add(new ExpandableLeftMenuItem(new LeftMenuItem(parent1Text,parent1Image,action1),new ArrayList<LeftMenuItem>())); 

mMenuItems.add(new ExpandableLeftMenuItem(new LeftMenuItem(parent2Text,parent2Image,action2),new ArrayList<LeftMenuItem>())); 

ArrayList<LeftMenuItem> parent3Children = new ArrayList<LeftMenuItem>(); 
parent3Children.add(new LeftMenuItem(parent3Child1TextId,parent3Child1ImageId,parent3Child1action)); 
parent3Children.add(new LeftMenuItem(parent3Child2TextId,parent3Child2ImageId,parent3Child2action)); 

mMenuItems.add(new ExpandableLeftMenuItem(new LeftMenuItem(parent1Text,parent1Image,action1),parent3Children)); 

Таким образом, вы обработали как детей и групп, чтобы принимать различные меры.

Я надеюсь, что это поможет.

+0

Да, я придумал то же самое решение, наконец, я ищу способ только иметь один onclicklistener, а затем определить, является ли строка группой или дочерним элементом с «экземпляром», но я не уверен, что это возможно –

Смежные вопросы