2015-04-25 105 views
0

自定義列表適配器類。android如何點擊列表視圖項中的按鈕來刪除該項

@Override 
public View getView(final int position, View convertView, ViewGroup parent) { 


    ViewHolder holder; 
    if(convertView == null) { 
     LayoutInflater inflater = (LayoutInflater) context 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     convertView = inflater.inflate(R.layout.cart_item, null); 
     holder = new ViewHolder(); 
     holder.image = (ImageView) convertView.findViewById(R.id.item_image); 
     holder.name = (TextView) convertView.findViewById(R.id.item_name); 
     holder.price = (TextView) convertView.findViewById(R.id.item_price); 
     holder.qty = (Spinner) convertView.findViewById(R.id.spinner_qty); 
     holder.delete_btn = (Button) convertView.findViewById(R.id.delete_btn); 
     convertView.setTag(holder); 

    }else{ 
     holder = (ViewHolder) convertView.getTag(); 
    } 

    //holder.image 
    holder.name.setText(productArray.get(position).getName()); 
    holder.price.setText("$"+ productArray.get(position).getPrice()); 
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, quantity); 
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    holder.qty.setAdapter(adapter); 
    return convertView; 
} 

如何點擊delete_btn刪除listview項。我不知道如何訪問列表視圖。請幫忙!

回答

0

添加這裏面getView():

 holder.delete_btn.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View view) { 
    yourlist.remove(position); 
    notifyDataSetChanged(); 
    } 
}); 
+0

是的我知道,問題是如何訪問listview然後調用它的remove方法 – Jerryc

+0

使用接口來溝通。您可以使用setTag方法 –

+0

將它傳遞給按鈕嗎?或者我以後再做謝謝@ PiotrGolinski – Jerryc

0

其實你需要選擇的項目位置也改變你的數據集(列表項)

所以你getView();

@Override 
public View getView(final int position, View convertView, ViewGroup parent) { 


    ViewHolder holder; 
    if (convertView == null) { 
     LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     ....... 
     holder.delete_btn = (Button) convertView.findViewById(R.id.delete_btn); 
     holder.delete_btn.setOnClickListener(new View.OnClickListener() {@Override 
      public void onClick(View view) { 
       //selected item position 
       int itemPosition=(int)view.getTag(); 
       //deletion stuff 
       productArray.remove(position); 
       notifyDataSetChanged(); 
      } 
     }); 
     convertView.setTag(holder); 

    } else { 
     holder = (ViewHolder) convertView.getTag(); 
    } 
    holder.delete_btn.setTag(position)//set item position 

    holder.name.setText(productArray.get(position).getName()); 
    ....... 
    return convertView; 
} 

更新: 檢查按鈕onClick監聽器方法。請參閱@Nikhil @nag

+0

確實定義了一個最終的int存儲位置工作?如何從列表視圖中刪除 – Jerryc

+0

如何通過@Nag發佈使用'yourList.remove(itemPosition);'內部onclick監聽器並調用'notifyDataSetChanged()' – Bharatesh

+0

如何獲取適配器類中的列表視圖 – Jerryc

相關問題