2013-12-03 3 views
1

У меня есть один фрагмент, в котором я разместил один вид расширяемого списка. У меня есть один модальный класс, который имеет список продуктов. В расширенном представлении списка в заголовке я хочу установить имя раздела, которое я успешно разместил, , а в качестве дочернего я хочу разместить продукты, которые подпадают под другое название раздела.Как использовать Expanadable listview с пользовательским объектом класса в framgent?

Но я получил только один продукт, когда применил свою логику. Вот что я получил ....!

enter image description here

Здесь я получил название только 1 продукт, который повторяется во всех продуктах.

Вот то, что я пытался до сих пор ::

Adapter ::

class ExpandableListAdapter extends BaseExpandableListAdapter { 

     private Context _context; 
     private ArrayList<String> _listDataHeader; // header titles 
     ArrayList<Products> topupProducts; 

     public ExpandableListAdapter(Context context, ArrayList<String> listDataHeader,ArrayList<Products> topupProducts) 
     { 
      this._context = context; 
      this._listDataHeader = listDataHeader; 
      this.topupProducts = topupProducts; 
     } 

     @Override 
     public Products getChild(int groupPosition, int childPosititon) { 

      /*return this.topupProducts.get(this._listDataHeader.get(groupPosition)) 
        .get(childPosititon);*/ 
      return topupProducts.get(childPosititon); 
     } 

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

     @Override 
     public View getChildView(int groupPosition, final int childPosition, 
       boolean isLastChild, View convertView, ViewGroup parent) { 

      // child = topupProducts.get(groupPosition).getProductName(); 
      //final String childText = (String) getChild(groupPosition, childPosition); 
      final String childText = topupProducts.get(groupPosition).getProductName(); 

      if (convertView == null) 
      { 
       LayoutInflater infalInflater = (LayoutInflater)_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
       convertView = infalInflater.inflate(R.layout.list_item_fragment, null); 
      } 

      convertView.setOnClickListener(new OnClickListener() { 
       @Override 
       public void onClick(View view) { 
        Toast.makeText(_context, topupProducts.get(childPosition).getProductID(),Toast.LENGTH_SHORT).show(); 
       } 
      }); 

      TextView txtListChild = (TextView) convertView.findViewById(R.id.lblListItem); 
      txtListChild.setText(childText); 
      return convertView; 
     } 

     @Override 
     public int getChildrenCount(int groupPosition) { 
      return this.topupProducts.size(); 
      //return ((ArrayList<String>) topupProducts.get(groupPosition)).size(); 
     } 

     @Override 
     public Object getGroup(int groupPosition) { 
      return this._listDataHeader.get(groupPosition); 
     } 

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

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

     @Override 
     public View getGroupView(int groupPosition, boolean isExpanded,View convertView, ViewGroup parent) 
     { 
      String headerTitle = (String) getGroup(groupPosition); 
      if (convertView == null) 
      { 
       LayoutInflater infalInflater = (LayoutInflater)_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
       convertView = infalInflater.inflate(R.layout.list_group, null); 
      } 

      TextView lblListHeader = (TextView) convertView.findViewById(R.id.lblListHeader); 
      lblListHeader.setTypeface(null, Typeface.BOLD); 
      lblListHeader.setText(headerTitle); 

      return convertView; 
     } 

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

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

Любая помощь будет оценена .. Спасибо заранее ...

EDIT: :

Вот как я получил свой продукт sectio п Имя из локальной базы данных (SQlite)

listHeader = new LinkedHashMap<String, String>(); 
DataHelper dataHelper=new DataHelper(ctx); 
topupProSectionsName=new ArrayList<String>(); 
topupProSectionID=new ArrayList<String>(); 
listHeader= dataHelper.getSectionSForTopupProduct(); 

if (listHeader != null) 
{ 
    Set entrySet = listHeader.entrySet(); 
    Iterator i = entrySet.iterator(); 
    while (i.hasNext()) 
    { 
     Map.Entry me = (Map.Entry)i.next(); 
     topupProSectionsName.add((String) me.getKey()); 
     topupProSectionID.add((String) me.getValue()); 
     addProduct((String)me.getKey(),listDataChild); 

    } 
} 

MyModal Класс ::

public class TopupProSectionName 
{ 
    private String sectionName; 
    private ArrayList<Products> topupProductList = new ArrayList<Products>(); 

    public String getsectionName() { 
     return sectionName; 
    } 
    public void setsectionName(String sectionName) { 
     this.sectionName = sectionName; 
    } 

    public ArrayList<Products> gettopupProductList() { 
     return topupProductList; 
    } 
    public void settopupProductList(ArrayList<Products> topupProductList) { 
     this.topupProductList = topupProductList; 
    } 
} 

AddProduct Метод ::

private int addProduct(String department,ArrayList<Products> product) 
    { 
     int groupPosition = 0; 

     TopupProSectionName headerInfo = myDepartments.get(department); 
     if(headerInfo == null) 
     { 
      headerInfo = new TopupProSectionName(); 
     } 
     headerInfo.setsectionName(department); 
     myDepartments.put(department, headerInfo); 
     deptList.add(headerInfo); 

     ArrayList<Products> productList = headerInfo.gettopupProductList(); 
     int listSize = productList.size(); 
     listSize++; 

     Products detailInfo = new Products(); 
     detailInfo.setProductName(product.get(groupPosition).getProductName()); 
     productList.add(detailInfo); 
     headerInfo.settopupProductList((productList)); 

     groupPosition = deptList.indexOf(headerInfo); 
     return groupPosition; 
    } 

Расширяемый адаптер Modified ::

class ExpandableListAdapter extends BaseExpandableListAdapter { 

     private Context _context; 
     ArrayList<Products> topupProducts; 
     ArrayList<TopupProSectionName> listDataHeader; 
     public ExpandableListAdapter(Context context, ArrayList<TopupProSectionName> listDataHeader) 
     { 
      this._context = context; 
      this.listDataHeader = listDataHeader; 
      this.topupProducts = topupProducts; 
     } 

     @Override 
     public Products getChild(int groupPosition, int childPosititon) { 

      ArrayList<Products> productList = deptList.get(groupPosition).gettopupProductList(); 
      return productList.get(childPosititon); 
     } 

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

     @Override 
     public View getChildView(int groupPosition, final int childPosition, 
       boolean isLastChild, View convertView, ViewGroup parent) { 


      final Products childText = (Products) getChild(groupPosition, childPosition); 


      if (convertView == null) 
      { 
       LayoutInflater infalInflater = (LayoutInflater)_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
       convertView = infalInflater.inflate(R.layout.list_item_fragment, null); 
      } 

      convertView.setOnClickListener(new OnClickListener() { 
       @Override 
       public void onClick(View view) { 
        //Toast.makeText(_context, topupProducts.get(childPosition).getProductID(),Toast.LENGTH_SHORT).show(); 
       } 
      }); 

      TextView txtListChild = (TextView) convertView.findViewById(R.id.lblListItem); 
      txtListChild.setText(childText.getProductName()); 
      return convertView; 
     } 

     @Override 
     public int getChildrenCount(int groupPosition) { 

      ArrayList<Products> productList = deptList.get(groupPosition).gettopupProductList(); 
      return productList.size(); 
     } 

     @Override 
     public Object getGroup(int groupPosition) { 

      return deptList.get(groupPosition); 
     } 

     @Override 
     public int getGroupCount() { 

      return deptList.size(); 
     } 

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

     @Override 
     public View getGroupView(int groupPosition, boolean isExpanded,View convertView, ViewGroup parent) 
     { 

      TopupProSectionName headerTitle = (TopupProSectionName) getGroup(groupPosition); 
      if (convertView == null) 
      { 
       LayoutInflater infalInflater = (LayoutInflater)_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
       convertView = infalInflater.inflate(R.layout.list_group, null); 
      } 

      TextView lblListHeader = (TextView) convertView.findViewById(R.id.lblListHeader); 
      lblListHeader.setTypeface(null, Typeface.BOLD); 
      lblListHeader.setText(headerTitle.getsectionName()); 

      return convertView; 
     } 

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

     @Override 
     public boolean isChildSelectable(int groupPosition, int childPosition) { 
      return true; 
     } 
    } 
+0

Взгляните на [SimpleExpandableListAdapter] (http://androidxref.com/4.4_r1/xref/frameworks/base/core/java/android/widget/SimpleExpandableListAdapter.java), вы должны изменить свои 'getChildrenCount' и' getChild'/структура данных. – Aprian

+0

@Aprian Спасибо за ваш быстрый ответ. Но я не могу понять, как изменить эту часть, не могли бы вы помочь мне немного больше? – AndroidLearner

ответ

2

структура будет что-то вроде этого:

List<String> groupList = new ArrayList<String>(); 
groupList.add("Group 1"); 
groupList.add("Group 2"); 

List<List<String>> childList = new ArrayList<List<String>>(); 
List<String> group1Childs = new ArrayList<String>(); 
group1Childs.add("Child 1 of Group 1"); 
group1Childs.add("Child 2 of Group 1"); 
childList.add(group1Childs); 
List<String> group2Child = new ArrayList<String>(); 
group2Childs.add("Child 1 of Group 2"); 
group2Childs.add("Child 2 of Group 2"); 
childLists.add(group2Childs); 

В вашем адаптере:

public int getChildCount(int groupPosition) { 
    return childList.get(groupPosition).size(); 
} 

public String getChild(int groupPosition, int childPosition) { 
    return childList.get(groupPosition).get(childPosition); 
} 

Надеется, что вы получите то, что я имел в виду. Это просто простой пример расширяемого списка, в вашем случае вы должны изменить String на Products.

Что я сделал

Я когда-то использовали один List структуру, как:

public class ExpandableItem { 
    private String groupName; 
    private List<String> childs; 
} 

Тогда я передал List<ExpandableItem> в Adapter конструктору _items

public int getChildCount(int groupPosition) { 
    return _items.get(groupPosition).getChilds().size(); 
} 

public String getChild(int groupPosition, int childPosition) { 
    return _items.get(groupPosition).getChilds().get(childPosition); 
} 

Я не знаю, является ли это хорошей практикой, но она работает.

+0

Большое вам спасибо за вашу помощь. Я изменил свой код в соответствии с вашим предложением, но теперь я получаю только один продукт в списке (в базе данных у меня есть 3 продукта ..) можете ли вы исправить меня, где я ошибаюсь? проверьте мою правку ... – AndroidLearner

+0

Возможно, ваша логика addProduct. Можете ли вы вручную добавить элементы первым и сообщить мне, если проблема сохраняется? Также, пожалуйста, поделитесь 'dataHelper.getSectionSForTopupProduct();' – Aprian

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