Android: Add event listeners to every item in a ListView

后端 未结 2 603
感情败类
感情败类 2020-12-21 05:49

I have an Android app with a ListView, and each row in the list has a TextView and a Button. What I want to do is add an OnClickListener to each Button in the ListView, but

2条回答
  •  萌比男神i
    2020-12-21 06:27

    It's not possible using SimpleCursorAdapter... you will have to create your own adapter. If you don't want to write a custom Adapter, at least try to enhance the SimpleCursorAdapter with new capabilities. For instance:

    public class YourAdapter extends SimpleCursorAdapter{
    
        public YourAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
            super(context, layout, c, from, to);
        }
    
        public View getView(int position, View convertView, ViewGroup parent){
            View view = super.getView(position, convertView, parent);
            Button button = (Button)view.findViewById(R.id.row_button);
            button.setOnClickListener(new View.OnClickListener() {
                @Override public void onClick(View v) {
                    Log.i(TAG, "clicked");
                }
            }); 
            return view;
        }
    }
    

    Then, you can do:

    SimpleCursorAdapter rows = new YourAdapter(this, R.layout.row_layout, cursor, from, to);
    setListAdapter(rows);
    

提交回复
热议问题