ListView onClickListener无法正常工作,并从ListView中删除行

时间:2013-09-19 05:33:29

标签: android listview android-listview listitem delete-row

list_item.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="5dp">

<TextView
    android:id="@+id/mytitle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="5dip"
    android:layout_marginTop="5dp"
    android:layout_toRightOf="@+id/icon"
    android:background="@drawable/textbox1"
    android:paddingBottom="10dp"
    android:text="Title"
    android:textColor="#CC0033"
    android:textSize="20dp" />

<ImageView
    android:id="@+id/icon"
    android:layout_width="wrap_content"
    android:layout_height="75dp"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/mytitle"
    android:layout_marginLeft="20dp"
    android:scaleType="fitXY"
    android:paddingLeft="10dp"
    android:paddingRight="10dp" />

<TextView
    android:id="@+id/descri"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/mytitle"
    android:layout_alignParentRight="true"
    android:layout_alignTop="@+id/icon"
    android:layout_marginTop="16dp"
    android:background="@drawable/textbox1"
    android:text="Description"
    android:textColor="#3399FF"
    android:textSize="14dp" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/mytitle"
    android:layout_toLeftOf="@+id/mytitle"
    android:layout_marginLeft="5dp"
    android:background="@drawable/buttontextview"
    android:text="       Click To Share"
    android:textColor="@android:color/white"
    android:textSize="13sp" />

这是我的 RowItem

public class RowItem {

       private String imagepath;
       private String title;
       private String desc;
       public boolean isclicked;

public RowItem(String imagepath,String title,String desc) {
    System.out.println("ImagePath is:---"+imagepath);
    this.imagepath = imagepath;
    System.out.println("Title is:---"+title);
    this.title = title;
    System.out.println("Description is:---"+desc);
    this.desc = desc;
    isclicked = false;
}

 public String getImagepath() {
    return imagepath;
}

public boolean isIsclicked() {
return isclicked;
  }

public void setIsclicked(boolean isclicked) {
this.isclicked = isclicked;
}

public void setImagepath(String imagepath) {
    this.imagepath = imagepath;
}


  public String getTitle() {
       return title;
  }
   public String getDesc() {
    return desc;
}

public void setDesc(String desc) {
    this.desc = desc;
}

public void setTitle(String title) {
    this.title = title;
        }
    @Override
   public String toString() {
         return title + "\n" + desc;
    }
 }

这是我在活动中的onCreate()方法

      {  int k = 0;
    if(i>0){
    rowItems = new ArrayList<RowItem>();
     for (int j = 0;j<i ; j++) {
         System.out.println("Loop Value:--"+j);
         System.out.println("Location Details:-----"+location.get(j));
         System.out.println("Description Details:------"+description.get(j));
         System.out.println("Image Details:------"+images.get(j));

            RowItem item = new RowItem(images.get(j),location.get(j),description.get(j));
            rowItems.add(item);
        }
        listView = (ListView) findViewById(R.id.list);
        adapter = new CustomListViewAdapter(PicActivity.this, rowItems);

        listView.setAdapter(adapter);           
          listView.setOnItemClickListener(this);
   }

这是我的listitem onClicklistner方法

    @Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    System.out.println("My List Item Clicked");
    mylistid = position;
    Button deleteBtn = (Button) findViewById(R.id.delete);
    deleteBtn.setOnClickListener(this);
    File myimagefile = new File(images.get(position));

    lastlistid = mydb.getlastlistid();
    int list = Integer.valueOf(lastlistid.get(0));
    listno=0 ;
    listno = list-position;
      SharedPreferences mylistpref = getSharedPreferences(Constants.listiddetails, 0);
    Editor edit= mylistpref.edit();
    edit.putInt("listid", listno);
    edit.commit();

    System.out.println("First Position Value:-"+position);
         Toast toast = Toast.makeText(getApplicationContext(),
            "Title " + (position + 1) + ": " + rowItems.get(position),
            Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
        toast.show();

        Intent intermediate = new Intent (PicActivity.this,InterMediateActivity.class);
        intermediate.putExtra("savenshare", "notshare");
        intermediate.putExtra("flag", "false");
        startActivity(intermediate);
        finish();
    }

Checkbox即将出现在列表视图中,但onItemclicklistner无效。

我的deleteButton onClicklistner就像这样

     case R.id.delete:
 System.out.println("My List item:-"+mylistid);
         ((CustomListViewAdapter)listView.getAdapter()).notifyDataSetChanged();
 break;

这里mylistid是我在listitemonclick上设置的全局整数。

为什么我的列表项onclicklistner不工作,如果我在列表中添加复选框,以及如何删除行并更新listitem.I已经遵循了许多教程但无法实现。

请帮助!!!!

更新

这是我的customListViewAdapter类

 public class CustomListViewAdapter extends BaseAdapter   {
private  List<RowItem> arr = new ArrayList<RowItem>();

ArrayList<Integer> checks=new ArrayList<Integer>();
private Context context;
Bitmap mybitmap;
private Activity activity;

ViewHolder holder = null;

int mypos=0;
File f;
RowItem rowItem;

public CustomListViewAdapter(Context context,List<RowItem> items) {
    //super();
    this.arr = items;
    this.context=context;
}

private class ViewHolder {
    //ImageView imageView;
    TextView txtTitle;
    TextView txtDesc;
    ImageView image;
  //  CheckBox mychk;

}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return arr.size();
}

@Override
public Object getItem(int arg0) {
    // TODO Auto-generated method stub
    //mypos=arg0;
    return arr.get(arg0);

}

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

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



rowItem = (RowItem) getItem(position);

    f = new File(rowItem.getImagepath());

System.out.println("My list item Position from GetView:--"+position);



LayoutInflater mInflater = (LayoutInflater) context
        .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

if (convertView == null) {
    convertView = mInflater.inflate(R.layout.list_item, null);
    holder = new ViewHolder();

    holder.txtDesc = (TextView) convertView.findViewById(R.id.descri);

    holder.txtTitle = (TextView) convertView.findViewById(R.id.mytitle);

 //   holder.mychk = (CheckBox) convertView.findViewById(R.id.checkBox1);

    holder.image = (ImageView) convertView.findViewById(R.id.icon);

 //   holder.mychk.setOnCheckedChangeListener(this);

//    holder.mychk.setTag(arr.get(position));

  //  holder.mychk.setChecked(false);

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

// holder.mychk.setOnCheckedChangeListener(this);

System.out.println("My Description is:--"+holder.txtDesc.getText());
System.out.println("My Title is:--"+holder.txtTitle.getText());

holder.txtDesc.setText("  "+rowItem.getDesc());

holder.txtTitle.setText("  "+rowItem.getTitle());
if(f.exists())
{
    mybitmap = BitmapFactory.decodeFile(f.getAbsolutePath());
    Bitmap myeditedbitmap = Bitmap.createScaledBitmap(mybitmap, 180, 150, false);

holder.image.setImageBitmap(myeditedbitmap);

//holder.mychk.setChecked(true);
//setImageResource(rowItem.getImagepath());
}
//holder.txtTitle.setText(rowItem.getTitle());

/* for(int i=0;i<ArrayId.size();i++)
{
  rowItem.remove(ArrayId[i]);
}
*/
return convertView;
    }



}







}

更新2

我已将ListItem xml更新为某些代码,现在onItemClick正在运行..

机器人:descendantFocusability = “blocksDescendants”

现在另一部分是..删除行项目..它仍然无效。如果我选​​择一个复选框,那么其他人也会被选中。如果我选​​择1 ..然后3..5..7正在被选中。如何避免这种情况?

我的deleteItem行代码..

    deleteBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                SparseBooleanArray checkedItemPositions =   listView.getCheckedItemPositions();
                 int itemCount = listView.getCount();

                 for(int i=itemCount-1; i >= 0; i--){
                     if(checkedItemPositions.get(i)){
                //         adapter.remove(rowItems.get(i));  This line is giving me error.first i want to delete row temp and give a toast message.then i will update the database later.but as i am using customarrayadapter class.so i dont have the method remove.Can someone help me regarding the remove method ?


                     }
                 }
                 checkedItemPositions.clear();
                 adapter.notifyDataSetChanged();
            }

        });

更新3

       case R.id.delete:

      SharedPreferences del = getSharedPreferences(Constants.checkedid,0);
        int checkmyid = 0;
        checkmyid = del.getInt("check", 0);

        int mycount = listView.getCount();

        System.out.println("My List item COUNT FROM DELETE METHOD:-"+mycount);  


                System.out.println("My List item FROM DELETE METHOD:-"+checkmyid);  

                rowItems.remove(checkmyid);
                 mydb.delete(checkmyid);




            ((CustomListViewAdapter)listView.getAdapter()).notifyDataSetChanged();
            break;

我的数据库中的Delete方法是

public void delete(int id){
    String sql = "delete from picdetails where id="+id;
    Cursor mych;
    mych = myDataBase.rawQuery(sql, null);
}

但是当我重新打开数据库时,数据再次显示。如何避免?此外,当我选择一个复选框以删除该特定复选框时,不会删除。最后一行将被删除。

更新4

我更新了删除按钮代码..现在行项目被删除..但是第一个选择它没有被删除。从底部删除。但是checkitemid是完美的

      SharedPreferences del = getSharedPreferences(Constants.checkedid,0);
       int checkmyid = 0;
       checkmyid = del.getInt("check", 0);

       int mycount = listView.getCount();

          System.out.println("My List item COUNT FROM DELETE METHOD:-"+mycount);

       SparseBooleanArray checked = listView.getCheckedItemPositions();

     System.out.println("*****My SELECTED List item FROM DELETE METHOD:-*****"+checkmyid);




        rowItems.remove(checkmyid);

2 个答案:

答案 0 :(得分:1)

ListView onClickListner not working

这是因为CheckBox在listitem布局中的可聚焦性。

将以下行添加到ListView的项目布局的根布局。

android:descendantFocusability="blocksDescendants"
list_item.xml

中的

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:layout_marginTop="5dp"
   android:descendantFocusability="blocksDescendants">

删除行(不确定,但如果进行一些更改则会起作用)

for(int i=0; i < itemCount; i++){
     if(checkedItem.contains(i)){
       View rowView=listView.getChildAt(i)  OR   listView.removeViewAt(i); 
       listView.removeView(rowView);


       //Also Remove data from **rowItems**  
     }
 }

这里checkedItem是arraylist(或其他)你应该检查listrow的商店位置。

答案 1 :(得分:0)

onClick...{

rowItems.remove(position);
   notifyDataSetChanged();
}

这应该有用......