2015-09-18 3 views
0

У меня возникли проблемы с внедрением expandableListView. Я осуществил мой ExpandableListAdapterВмешательство между дочерними элементами expandableListView

общественного класс ExpandableListAdapter расширяет BaseExpandableListAdapter {

private static final int SUM = 1; 
private static final int SUB = 2; 

private Context context; 
private List<String> listDataHeader; //Header titles 
private HashMap<String, List<Article>> listDataChild; 
private HashMap<Integer, Bitmap> productImagesHashMap; 

public ExpandableListAdapter (Context context, List<String> listDataHeader, HashMap<String, List<Article>> listDataChild, HashMap<Integer, Bitmap> productImagesHashMap) { 
    this.context = context; 
    this.listDataHeader = listDataHeader; 
    this.listDataChild = listDataChild; 
    this.productImagesHashMap = productImagesHashMap; 
} 

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

@Override 
public int getChildrenCount(int groupPosition) { 
    return this.listDataChild.get(this.listDataHeader.get(groupPosition)).size(); 
} 

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

@Override 
public Object getChild(int groupPosition, int childPosition) { 
    return this.listDataChild.get(this.listDataHeader.get(groupPosition)).get(childPosition); 
} 

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

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

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

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

    String headerTitle = (String) getGroup(groupPosition); 
    if (convertView == null) { 
     LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     convertView = layoutInflater.inflate(R.layout.user_expand_listview_header, null); 
    } 

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

    return convertView; 
} 

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

    final Article childValues = (Article) getChild(groupPosition, childPosition); 

    if (convertView == null) { 
     LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     convertView = layoutInflater.inflate(R.layout.product_row, null); 
    } 

    Integer articleId = childValues.getId(); 

    final TextView articleIdTextView = (TextView) convertView.findViewById(R.id.product_id); 
    ImageView productImageTextView = (ImageView) convertView.findViewById(R.id.product_image); 
    TextView productNameTextView = (TextView) convertView.findViewById(R.id.product_name); 
    TextView productDescriptionTextView = (TextView) convertView.findViewById(R.id.product_description); 
    final TextView productPriceTextView = (TextView) convertView.findViewById(R.id.product_price); 

    articleIdTextView.setText(articleId.toString()); 
    productImageTextView.setImageBitmap(productImagesHashMap.get(articleId)); 
    productNameTextView.setText(childValues.getNome()); 
    productDescriptionTextView.setText(childValues.getDescrizione()); 
    productPriceTextView.setText(childValues.getPrezzo()); 

    ImageButton addButton = (ImageButton) convertView.findViewById(R.id.add_btn); 
    final TextView articleQty =(TextView) convertView.findViewById(R.id.product_qnty); 
    ImageButton removeButton = (ImageButton) convertView.findViewById(R.id.remove_btn); 

    addButton.setOnClickListener(new Button.OnClickListener() { 

     @Override 
     public void onClick(View view) { 
      if (context instanceof UserActivity) { 
       ((UserActivity) context).updateTotal(
         Integer.parseInt(articleIdTextView.getText().toString()), 
         productPriceTextView.getText().toString(), 
         SUM); 
       articleQty.setText(updateProductQty(articleQty, SUM)); 
      } 
     } 
    }); 

    removeButton.setOnClickListener(new Button.OnClickListener() { 

     @Override 
     public void onClick(View view) { 
      if (context instanceof UserActivity) { 
       ((UserActivity) context).updateTotal(
         Integer.parseInt(articleIdTextView.getText().toString()), 
         productPriceTextView.getText().toString(), 
         SUB); 
       articleQty.setText(updateProductQty(articleQty, SUB)); 
      } 
     } 
    }); 

    return convertView; 
} 

@Override 
public boolean isChildSelectable(int i, int i1) { 
    return true; 
} 

private String updateProductQty(TextView productQty, int operation) { 
    Integer qty = Integer.parseInt(productQty.getText().toString()); 
    switch (operation) { 
     case 1: //SUM 
      qty += 1; 
      break; 
     case 2: //SUB 
      if (qty > 0) 
       qty -= 1; 
      break; 
    } 
    return qty.toString(); 
} 

}

Есть некоторые продукты, которые считываются из базы данных и вставленные в ExpandableListView по типу (на самом деле ручки, ноутбуки и Бумага). Затем есть две кнопки, которые позволяют выбрать, сколько из них пользователь хочет купить, количество отслеживается TextView. Теперь, когда я реализовал это с обычным ListView все сработало, но с ExpandableListView есть помехи между количеством TextView детей.

Например, фактический состав ExpandableListView является то, что:

Ручки

- Black Pen

- Blue Pen

- Red Pen

Ноутбуки

- Черный ноутбук

- Синий ноутбук

- Красный ноутбук

Бумага

- А4

Если пользователь добавить черный ноутбук, синее перо также добавило

Если пользователь добавляет синий блокнот, добавляется черная ручка

Если пользователь добавляет красный блокнот, также добавляется синяя ручка

Почему существуют такие помехи?

+0

Неужели вы пытаетесь отладить? –

ответ

0

Вы не отслеживаете количество обновленных обновлений.

С ExpandableListView - как ListView - перерабатывает свои взгляды, вы получите такое поведение:

  • прессы пользователя Добавить кнопку для черного ноутбука.
  • Пользователь прокручивает/расширяет/сворачивает список.
  • Просмотр для синего пера создается путем переработки вид из черного ноутбука.
  • Вид на синюю ручку отображается с количеством черного ноутбука.

Это то, что вам нужно сделать:

  • Добавьте свойство количества в Article класса
  • При создании вид ребенка, заполнить articleQtyTextView с количеством содержащегося в этом Article объекта.
  • Когда пользователь нажимает кнопки «Добавить/Удалить», обновите количество в объекте Article и позвоните по телефону notifyDataSetChanged().

Правило: вид заселен из модели, модель обновляется от слушателя. Не используйте прослушиватель для обновления представления, позаботятся об этом notifyDataSetcChanged().

+0

Thaks, это работает! Это то, что я знаю: D – Fededark

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