How do I get the row ID of the row from a ListView, which contains a clickable item?

前端 未结 2 588
离开以前
离开以前 2021-01-14 11:25

Before I added a button to the layout XML for my rows, the row ID was returned in the callback onListItemClick() upon a list item being clicked. Now that I added a button to

2条回答
  •  梦毁少年i
    2021-01-14 12:12

    you have to take little diff aproach you have to create your own cursorAdapter if it SimpleCursorAdapter then code will be some thing like this

    first create a subclass of cursoradapter then override getView Method and then define onclicklistener for them

    public class SMSimpleCursorAdapter extends SimpleCursorAdapter{
    
    Context context;
    Activity activity;
    public SMSimpleCursorAdapter(Context context, int layout, Cursor c,
            String[] from, int[] to) {
        super(context, layout, c, from, to);
        this.context=context;
        this.activity=(Activity) context;
    }
    
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        View view = super.getView(position, convertView, parent);
        long id=getItemId(position);
        Button button = (Button)view.findViewById(R.id.btnDelete);
         //pass id in your handler
        button.setOnClickListener(new DeleteItemHandler(id, activity,this));        
    }
    

    and your handle class will be something like this

    public class DeleteItemHandler implements OnClickListener,
            android.view.View.OnClickListener {
    long id;
    Activity activity;
    SMSimpleCursorAdapter smSimpleCursorAdapter;
    public DeleteItemHandler(long id, Activity activity,
            SMSimpleCursorAdapter smSimpleCursorAdapter) {
        super();
        this.id = id;
        this.activity = activity;
        this.smSimpleCursorAdapter = smSimpleCursorAdapter;
    }
    @Override
    public void onClick(View v) {
              //your own item click code
    }
    }
    

提交回复
热议问题