2013-08-18 3 views
1

У меня есть представление, где строки добавляются через представление списка. Элемент списка имеет следующие горизонтальные значения: checkbox -Checkbox, Имя элемента - textView, минус кнопка - Изображение, количество - textview, кнопка добавления. - ImagebuttonAndroid List View on Click position

Мне нужно обновить количество, основанное на добавлении или минусовом щелчке. Я в состоянии получить положение кнопки добавить через GetTag(), но не смог получить соответствующее количество для обновления it.Below является адаптер класса

public class CustomAdapter extends BaseAdapter { 

    private List<String> mListItems; 
    private LayoutInflater mLayoutInflater; 
    private Context mContext; 
    ItemDBAdapter itemDB; 
    ViewHolder holder; 
    int a =1; 
    public CustomAdapter(Context context,ArrayList<String> arrayList){ 

     mContext=context; 
     mListItems=arrayList; 
     mContext=context; 
     //get the layout inflater 
     mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    } 
    @Override 
    public int getCount() { 
     // TODO Auto-generated method stub 
     return mListItems.size(); 
    } 

    @Override 
    public Object getItem(int position) { 
     // TODO Auto-generated method stub 
     return null; 
    } 

    @Override 
    public long getItemId(int arg0) { 
     // TODO Auto-generated method stub 
     return 0; 
    } 


     private static class ViewHolder { 

      TextView itemName,quantity; 
       CheckBox checkbox; 
       ImageButton addBtn,minusBtn; 



     } 
     @Override 

     public View getView(int position, View convertview, ViewGroup viewGroup) { 

      // create a ViewHolder reference 


      //check to see if the reused view is null or not, if is not null then reuse it 
      if (convertview == null) { 
       holder = new ViewHolder(); 


       convertview = mLayoutInflater.inflate(R.layout.list_item, null); 



       /* holder.itemName=new TextView(mContext); 
       holder.checkbox=new CheckBox(mContext); 
       holder.quantity=new TextView(mContext); 
       holder.addBtn=new ImageButton(mContext); 
       holder.minusBtn=new ImageButton(mContext)*/; 

       holder.itemName = (TextView) convertview.findViewById(R.id.item_name); 
       holder.addBtn = (ImageButton) convertview.findViewById(R.id.add); 
       holder.minusBtn = (ImageButton) convertview.findViewById(R.id.minus); 
       holder.quantity = (TextView) convertview.findViewById(R.id.item_quantity); 
       holder.checkbox = (CheckBox) convertview.findViewById(R.id.cbBox); 
       holder.checkbox.setOnCheckedChangeListener(checkListener); 
       holder.checkbox.setTag(position); 
       holder.minusBtn.setImageResource(R.drawable.minus); 
       holder.quantity.setText(String.valueOf(a)); 
       holder.quantity.setTag(position); 
       holder.addBtn.setImageResource(R.drawable.add); 
       holder.addBtn.setOnClickListener(addBtnClick); 
       holder.addBtn.setTag(position); 
       //holder.minusBtn.setOnClickListener(minusBtnClick); 
       holder.minusBtn.setTag(position); 

       // the setTag is used to store the data within this view 
       convertview.setTag(holder); 
      } else { 
       // the getTag returns the viewHolder object set as a tag to the view 
       holder = (ViewHolder)convertview.getTag(); 
      } 

      //get the string item from the position "position" from array list to put it on the TextView 
      String stringItem = mListItems.get(position); 

      if (stringItem != null) { 
       if (holder.itemName != null) { 
        //set the item name on the TextView 
        holder.itemName.setText(stringItem); 
       } 
     } 

      //this method must return the view corresponding to the data at the specified position. 
      return convertview; 

     } 


     private OnClickListener addBtnClick = new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stube 
       int b = (Integer) v.getTag(); 
       a = a + 1; 
       holder.quantity.setText(String.valueOf(a)); 

      } 
     }; 



} 

Поскольку величина не кликабельны, я не могу получить конкретное положение для обновления количества. Пожалуйста, порекомендуйте. Благодарю.

+0

'holder.quantity.setText (String.valueof (a))' a - это int. почему количество не кликабельно? – Raghunandan

+0

Спасибо за вход Рагхунандан. Я использовал выше только для установки текста (ошибка Typo при публикации). Это не работает. Я могу получить правильную позицию нажатия кнопки, но количество не обновляется. – Gaurav

+0

если количество говорит 1, то вы нажимаете кнопку в строке, которую вам нужно сделать 2? – Raghunandan

ответ

1

Попробуйте ниже

В onClick

private OnClickListener addBtnClick = new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      View view = (View) v.getParent(); 
      TextView tv = (TextView) view.findViewById(R.id.item_quantity); 
      int value = Integer.parseInt(tv.getText().toString()); 
      value=value+1; 
      tv.setText(String.valueOf(value)); 
     } 
    }; 

Edit: Лучше использовать a ViewHolder для плавной прокрутки и производительности

http://developer.android.com/training/improving-layouts/smooth-scrolling.html

+0

Большое спасибо Рагхунандану. Его работа, но только при первом нажатии. Когда я нажимаю первый раз его изменяющееся значение от 1 до 2, но при втором нажатии его не работает. Значение остается 2. – Gaurav

+0

@Gaurav обновит мое сообщение – Raghunandan

+0

@Gaurav попробует отредактировать теперь нет необходимости устанавливать тег. если это помогает, не забудьте принять и перенести ответ – Raghunandan

0

В if (convertView == null) блок просто получает ссылку на представления и setTag для них, в противном случае часть получает предыдущий тег. Применить все другие вещи после еще

изменить код что-то вроде этого ....

public View getView(int position, View convertview, ViewGroup viewGroup) { 

     // create a ViewHolder reference 


     //check to see if the reused view is null or not, if is not null then reuse it 
     if (convertview == null) { 
      holder = new ViewHolder(); 


      convertview = mLayoutInflater.inflate(R.layout.list_item, null); 

      holder.itemName = (TextView) convertview.findViewById(R.id.item_name); 
      holder.addBtn = (ImageButton) convertview.findViewById(R.id.add); 
      holder.minusBtn = (ImageButton) convertview.findViewById(R.id.minus); 
      holder.quantity = (TextView) convertview.findViewById(R.id.item_quantity); 
      holder.checkbox = (CheckBox) convertview.findViewById(R.id.cbBox); 



      // the setTag is used to store the data within this view 
      convertview.setTag(holder); 
     } else { 
      // the getTag returns the viewHolder object set as a tag to the view 
      holder = (ViewHolder)convertview.getTag(); 
     } 

     holder.checkbox.setOnCheckedChangeListener(checkListener); 
          holder.minusBtn.setImageResource(R.drawable.minus); 
      holder.quantity.setText(String.valueOf(a)); 

      holder.addBtn.setImageResource(R.drawable.add); 
      holder.addBtn.setOnClickListener(addBtnClick); 
         //get the string item from the position "position" from array list to put it on the TextView 
     String stringItem = mListItems.get(position); 

     if (stringItem != null) { 
      if (holder.itemName != null) { 
       //set the item name on the TextView 
       holder.itemName.setText(stringItem); 
      } 
    } 

     //this method must return the view corresponding to the data at the specified position. 
     return convertview; 

    } 
+0

Спасибо Kettu. Я попробовал ответ Рагхунандана выше, и это сработало. – Gaurav

+0

Прохладный .. вы получили то, что хотели. –