2015-02-06 11 views
0

Я создал ExpandableListAdapter от this tutorial (большое спасибо!) За сортировку товаров по группам. Но я должен был сделать какую-то ошибку, потому что некоторые продукты находятся в неправильной группе, некоторые продукты во многих группах, а некоторые продукты даже не видны (показаны).ExpandableListAdapter дает неправильный результат

Ниже приведено ExpandableListAdapter и код для заполнения данных на Map<String, List<Product>> (для товаров) и List<String> (для групп).

адаптер:

class ExpandableListAdapter extends BaseExpandableListAdapter { 

    private Context _context; 
    private List<String> _listDataHeader; // header titles 
    // child data in format of header title, child title 
    private Map<String, List<Product>> _listDataChild; 
    private boolean viewOnly; 
    private Config config; 

    public ExpandableListAdapter(Context context, List<String> listDataHeader, 
      Map<String, List<Product>> listChildData, boolean viewOnly, Config config) { 
     this._context = context; 
     this._listDataHeader = listDataHeader; 
     this._listDataChild = listChildData; 
     this.viewOnly = viewOnly; 
     this.config = config; 
     /* 
     * THIS GIVES ME RIGHT PAIRS (GROUP : PRODUCT) 
     * 

     int y = 0; 
     int i = 1; 

     for (Entry<String, List<Product>> entry : this._listDataChild.entrySet()) { 
       String key = entry.getKey(); 
       List<Product> value = entry.getValue(); 
       for(Product valuee : value){ 
        Log.v("PRODUCTS list", i + " GROUP: " + key + " VALUE: " + valuee.getName()); 
        Log.v("GROUPS list", i + " GROUP: " + this._listDataHeader.get(y) + " VALUE: " + valuee.getName()); 
        i++; 
       } 
       y++; 

     } 
     */ 

    } 


    @Override 
    public Object getChild(int groupPosition, int childPosititon) { 
     return this._listDataChild.get(this._listDataHeader.get(groupPosition)) 
       .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 Product product = (Product) getChild(groupPosition, childPosition); 

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

      CheckBox name = (CheckBox) convertView.findViewById(R.id.product_item_checkbox); 
      TextView price_value = (TextView) convertView.findViewById(R.id.product_item_price_value); 
      TextView price_value_vo = (TextView) convertView.findViewById(R.id.product_item_price_value_vo); 
      TextView price_textview = (TextView) convertView.findViewById(R.id.product_item_price_textview); 
      DatePicker from = (DatePicker) convertView.findViewById(R.id.product_item_datePicker_from); 
      EditText serial_number = (EditText) convertView.findViewById(R.id.product_item_edittext); 
      serial_number.addTextChangedListener(new GenericTextWatcherCustom(product)); 
      TextView item_lenght = (TextView) convertView.findViewById(R.id.product_item_lenght); 
      TextView item_lenght_vo = (TextView) convertView.findViewById(R.id.product_item_lenght_vo); 
      TextView item_type = (TextView) convertView.findViewById(R.id.product_item_type); 
      TextView item_type_vo = (TextView) convertView.findViewById(R.id.product_item_type_vo); 
      TextView name_only = (TextView) convertView.findViewById(R.id.product_item_name); 

      name.setOnClickListener(new View.OnClickListener() { 
       public void onClick(View v) { 
        CheckBox cb = (CheckBox) v ; 
        Product product = (Product) cb.getTag(); 
        product.setSelected(cb.isChecked()); 
       } 
      }); 


      DatePicker.OnDateChangedListener mDateListenerFrom = new DatePicker.OnDateChangedListener() { 

       @Override 
       public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) { 
        Product product = (Product) view.getTag(); 
        @SuppressWarnings("deprecation") 
        Date date = new Date(year - 1900,monthOfYear,dayOfMonth); 
        product.setFrom(date); 
       } 
      }; 

      Calendar cal = product.getActive_toDate(); 
      if (cal == null){ 
       cal = Calendar.getInstance(); 
      } 
      Date date = new Date(cal.get(Calendar.YEAR) - 1900,cal.get(Calendar.MONTH),cal.get(Calendar.DAY_OF_MONTH)); 
      from.setMinDate(date.getTime()); 
      from.init(cal.get(Calendar.YEAR),cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), mDateListenerFrom); 
      product.setFrom(date); 


      //quantity.setTag(product); 
      name.setTag(product); 
      from.setTag(product); 
      name.setChecked(product.getSelected()); 
      name.setText(product.getName()); 
      name_only.setText(product.getName()); 
      name_only.setVisibility(8); 
      item_lenght_vo.setVisibility(8); 
      item_type_vo.setVisibility(8); 
      price_value.setText(product.getPrice()); 
      price_value_vo.setText(product.getPrice()); 
      price_value_vo.setVisibility(8);    

      if (product.getUnit().compareTo("hardware") == 0){ 
       from.setVisibility(DatePicker.INVISIBLE); 
       serial_number.setVisibility(EditText.VISIBLE); 
       serial_number.setText(product.getSerial_number()); 
       item_lenght_vo.setText(product.getUnit()); 
       item_lenght.setText(product.getUnit()); 
       item_type.setText("Serial number"); 
      }else{ 
       serial_number.setVisibility(DatePicker.INVISIBLE); 
       from.setVisibility(EditText.VISIBLE); 
       if (config.getConfig_change_sales_date().compareTo("0") == 0){ 
        from.setEnabled(false); 
       } 
       item_lenght.setText(product.getUnit_length() + " " + product.getUnit()); 
       item_lenght_vo.setText(product.getUnit_length() + " " + product.getUnit()); 
       item_type.setText("Product start"); 
      } 

      if (viewOnly){ 
       name_only.setVisibility(0); 
       name.setVisibility(8); 
       from.setVisibility(8);     
       serial_number.setVisibility(8); 
       item_type_vo.setVisibility(0); 
       item_type.setVisibility(8); 
       item_lenght.setVisibility(8); 
       item_lenght_vo.setVisibility(0); 
       item_lenght_vo.setTextColor(Color.LTGRAY); 
       price_value.setVisibility(8); 
       price_value_vo.setVisibility(0); 
       price_value_vo.setTextColor(Color.LTGRAY); 
       price_textview.setVisibility(8); 
       historyButton.setVisibility(8); 

       // Height adjustment of product box 
       convertView.setLayoutParams(new ListView.LayoutParams(ListView.LayoutParams.MATCH_PARENT, ListView.LayoutParams.WRAP_CONTENT)); 


       // backButton to the whole width 
       backButton.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f)); 


       // Set the same width 
       Display display = getWindowManager().getDefaultDisplay(); 
       @SuppressWarnings("deprecation") 
       int width = display.getWidth(); 

       name_only.measure(MeasureSpec.UNSPECIFIED,MeasureSpec.UNSPECIFIED); 
       item_lenght_vo.measure(MeasureSpec.UNSPECIFIED,MeasureSpec.UNSPECIFIED); 


       if(name_only.getMeasuredWidth() < item_lenght_vo.getMeasuredWidth()) { 
        name_only.setLayoutParams(new RelativeLayout.LayoutParams(item_lenght_vo.getMeasuredWidth(), LayoutParams.WRAP_CONTENT)); 
       } 
       else { 
        RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(name_only.getMeasuredWidth(), LayoutParams.WRAP_CONTENT); 
        rl.addRule(RelativeLayout.BELOW, R.id.product_item_name); 
        rl.topMargin = 10; 
        item_lenght_vo.setLayoutParams(rl); 
       }; 

       RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
       params.setMargins(70, 0, 0, 0); 
       params.addRule(RelativeLayout.RIGHT_OF, R.id.product_item_name); 
       item_type_vo.setLayoutParams(params); 
       RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
       params2.setMargins(70, 10, 0, 0); 
       params2.addRule(RelativeLayout.BELOW, R.id.product_item_name); 
       params2.addRule(RelativeLayout.RIGHT_OF, R.id.product_item_name); 
       price_value_vo.setLayoutParams(params2); 
      }; 

     } 
     return convertView; 
    } 

    @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 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) this._context 
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      convertView = infalInflater.inflate(R.layout.group_separator, null); 
     } 

     TextView group_name = (TextView) convertView.findViewById(R.id.product_group_name); 
     group_name.setText(headerTitle);//product.getGroup_name()); 

     return convertView; 
    } 

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

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


} 

Заполнение данных: (нет никаких проблем, все понятно и работает отлично)

public void createProductList(){ 
     Boolean viewOnly = type.compareTo("Product") == 0 ? true : false; 


     try { 
      product = products.get(0);  
      // ArrayList<Map<String,List<Product>> products 
      // Map<String,List<Product> product 
      for(Entry<String, List<Product>> entry: product.entrySet()){ 
       String key = entry.getKey(); 
       groups.add(key);   
       // List<String> 
      } 
     } catch (Exception e) { 
      Log.e("MSG", e.toString()); 
     } 

     dataAdapter = new ExpandableListAdapter(this,groups,product,viewOnly,config); 
     // Assign adapter to ListView 
     productList.setAdapter(dataAdapter); 
    } 

Adapter хорошо, работает хорошо, не исключение ошибок, просто неправильно сортировка по группам. Я не знаю, что случилось. Какие-либо предложения?

ответ

0

Предполагая, что listDataHeader и listChildData правильно сохраняют свои данные, я бы сказал, что проблема связана с вашим методом getChildView(). Это довольно сложный и трудно определить, но, похоже, вы делаете следующее:

public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { 
    if (convertView == null) { 
     //Inflating, setting listeners, filling with data 
    } 

    //I don't see anything being done when the convertView is not null? 
} 

Вы должны делать:

public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { 
    if (convertView == null) { 
     //Inflating 
    } 

    //setting listeners, filling with data 
} 

Я мог бы быть неправильно, и вы делаете это. Трудно сказать в публикации. Здесь используется среда IDE.

Обратите внимание, что вы должны использовать парадигму ViewHolder. Это очень поможет в производительности и почти всегда будет необходимо для любой реализации адаптера. Вот brief run down and example. Это в нижней части блога.

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