删除一行listview android

时间:2014-01-21 07:22:52

标签: android listview

我正在尝试使用自定义列表视图在删除图像按钮的每一行中创建包含标题,描述和其他数据的列表。

当我点击第10行的ImageButton时,ListView的第5行将被删除!

enter image description here

myadapter:

public  static class ViewHolder {
    TextView favorites_title;
    TextView favorites_description;
    TextView favorites_date;
    ImageButton favorites_btn_delete ;
}

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

    ViewHolder holder;
    if(convertView==null){
        /****** Inflate tabitem.xml file for each row ( Defined below ) *******/
        convertView = inflater.inflate(R.layout.favorites_list_row_layout, null);

        /****** View Holder Object to contain tabitem.xml file elements ******/

        holder = new ViewHolder();
        holder.favorites_title = (TextView) convertView.findViewById(R.id.favorites_title);
        holder.favorites_description = (TextView) convertView.findViewById(R.id.favorites_description);
        holder.favorites_date = (TextView) convertView.findViewById(R.id.favorites_date);
        holder.favorites_btn_delete = (ImageButton)convertView.findViewById(R.id.favorites_btn_delete); 
       /************  Set holder with LayoutInflater ************/
        convertView.setTag( holder );
        holder.favorites_btn_delete.setTag(position);
    }
    else 
        holder=(ViewHolder)convertView.getTag();
    holder.favorites_btn_delete.getTag();
    NewsItem newsItem = (NewsItem) listData.get(position);

    holder.favorites_title.setText(newsItem.getHeadline());
    holder.favorites_description.setText(newsItem.getDescription());
    holder.favorites_date.setText(newsItem.getDate());
    holder.favorites_btn_delete.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Integer index = (Integer) v.getTag();
            int i = index.intValue();
            Log.e("Position",  String.valueOf(i));
        //  listData.remove(i);
        //  notifyDataSetChanged();

        }
    });

3 个答案:

答案 0 :(得分:1)

holder.favorites_btn_delete.setTag(position);移到if else之外,否则当position不为空时,Button中的新convertView值永远不会设置为标记旧值将保留为标记

答案 1 :(得分:0)

holder.favorites_btn_delete.setOnClickListener(本);

getview方法之外的

public void onClick(View v)
    {
  // TODO Auto-generated method stub
            Integer index = (Integer) v.getTag();
            int i = index.intValue();
            Log.e("Position",  String.valueOf(i));
          listData.remove(i);
        notifyDataSetChanged();

}

答案 2 :(得分:0)

使用此代码..这将有助于你..

在图像按钮上应用onItem单击侦听器

@Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
         listData.remove(positon);
        notifyDataSetChanged();
    }

将此应用于您的活动。