ListView控件中item中实现的Button的点击事件

本文介绍如何在Android Listview的Item中实现Button的点击事件,通过自定义适配器和ViewHolder模式,使得每个列表项的Button都能响应点击操作,并删除对应的联系人数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.适配器我们可以简单的理解为数据与控件之间交互的桥梁,如果我们想要实现在Listview控件之中实现Button的点击事件,就需要把当前的UI线程传进Adapter之中,因此要在Adapter之中设置监听器,即适配器中创建setOnClickListener方法,适配器中定义了ViewHolder静态类定义了button控件,此时需要ViewHolder类中创建setOnClickListener方法,将传进适配器的UI线程,传进ViewHolder类中,然后用button的监听器事件将UI线程传进去,如下图所示:


2.示例代码如下:

1)Listview的item中的布局文件需要设置:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent"

              android:descendantFocusability="blocksDescendants"

        >

    <TextView
            android:id="@+id/item_cc_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

    <Button
            android:id="@+id/item_cc_del"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="删除"
            />

</LinearLayout>
2)这里由于需要将内容提供者中的数据加载到Listview中,我们自定义了CursorAdapter适配器。

/**
 * CursorAdapter 内部已经实现了 视图的复用,不需要再处理了
 */
public class MyDataAdapter extends CursorAdapter {

    private View.OnClickListener mOnClickListener;

    public MyDataAdapter(Context context, Cursor c, int flags) {
        super(context, c, flags);
    }

    public void setOnClickListener(View.OnClickListener onClickListener) {
        mOnClickListener = onClickListener;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        ViewHolder holder = (ViewHolder) view.getTag();
        holder.bindView(cursor);
    }

    /**
     * 创建布局
     *
     * @param context
     * @param cursor
     * @param parent
     * @return
     */
    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View ret = null;

        ret = LayoutInflater.from(context).inflate(R.layout.item_cc, parent, false);

        ViewHolder holder = new ViewHolder(ret);

        holder.setOnClickListener(mOnClickListener);

        ret.setTag(holder);

        return ret;
    }

    private static class ViewHolder {
        private TextView mTxtName;
        private Button mBtnDel;

        private View.OnClickListener mOnClickListener;

        public ViewHolder(View itemView){
            mTxtName = (TextView) itemView.findViewById(R.id.item_cc_name);
            mBtnDel = (Button) itemView.findViewById(R.id.item_cc_del);
        }

        public void setOnClickListener(View.OnClickListener onClickListener) {
            mOnClickListener = onClickListener;
            mBtnDel.setOnClickListener(onClickListener);
        }

        public void bindView(Cursor cursor){

            int index = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            String str = cursor.getString(index);
            mTxtName.setText(str);

            index = cursor.getColumnIndex(ContactsContract.Contacts._ID);
            long id = cursor.getLong(index);
            mBtnDel.setTag(id);
        }
    }


}
3).UI线程的示例代码:

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener, View.OnClickListener {

    private MyDataAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    private void initView() {

        ListView listView = (ListView) findViewById(R.id.contact_list);

        ContentResolver resolver = getContentResolver();
        // 获取联系人列表,指定名称列
        Cursor cursor = resolver.query(
                ContactsContract.Contacts.CONTENT_URI,
                new String[]{
                        ContactsContract.Contacts._ID,  // _ID必须存在,显示在ListView时
                        ContactsContract.Contacts.DISPLAY_NAME
                },
                null,
                null,
                null
        );

        //mAdapter = new SimpleCursorAdapter(
        //        this,
        //        R.layout.item_cc,
        //        cursor,
        //        new String[]{
        //                ContactsContract.Contacts.DISPLAY_NAME
        //        },
        //        new int[]{R.id.item_cc_name},
        //        CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER
        //);

        mAdapter = new MyDataAdapter(this, cursor, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        //
        mAdapter.setOnClickListener(this);

        listView.setAdapter(mAdapter);

        listView.setOnItemClickListener(this);

        listView.setOnItemLongClickListener(this);
    }

    private void init() {

        ContentResolver resolver = getContentResolver();

        // 获取联系人列表,指定名称列
        Cursor cursor = resolver.query(
                ContactsContract.Contacts.CONTENT_URI,
                new String[]{
                        ContactsContract.Contacts.DISPLAY_NAME,
                },
                null,
                null,
                null
        );

        if (cursor != null) {

            while (cursor.moveToNext()) {
                int index = cursor.getColumnIndex(
                        ContactsContract.Contacts.DISPLAY_NAME
                );
                if (index != -1) {
                    String name = cursor.getString(index);
                    Log.d("Contact", "name = " + name);
                }
            }

            cursor.close();
        }

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // id 就是联系人 id
        // select * from data where contact_id = id and type = phone

        ContentResolver resolver = getContentResolver();

        // 获取一个联系人的所有手机号,那么使用 Phone 这个类
        Cursor cursor = resolver.query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null,
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?",
                new String[]{Long.toString(id)},
                null
        );

        if (cursor != null) {
            while (cursor.moveToNext()) {
                // 获取手机号的列
                int index = cursor.getColumnIndex(
                        ContactsContract.CommonDataKinds.Phone.NUMBER
                );

                if (index != -1) {
                    String phone = cursor.getString(index);
                    Log.d("Phone", "email = " + phone);
                }
            }
            cursor.close();
        }

    }

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

        boolean b = false;

        // 1. ContentResolver
        // 2. delete + where

        ContentResolver resolver = getContentResolver();


        // 3. 删除联系人,必须要使用 RawContacts 表
        // delete from raw_contacts where contact_id=id
        int num = resolver.delete(
                ContactsContract.RawContacts.CONTENT_URI,
                ContactsContract.RawContacts.CONTACT_ID + "=?",
                new String[]{Long.toString(id)}
        );

        if (num > 0) {
            requeryCursor();
        }

        return b;
    }

    public void requeryCursor() {
        ContentResolver resolver = getContentResolver();
        Cursor cursor = resolver.query(
                ContactsContract.Contacts.CONTENT_URI,
                null,
                null,
                null,
                null
        );
        mAdapter.changeCursor(cursor);
    }

    @Override
    public void onClick(View v) {
        Object tag = v.getTag();
        Long id = (Long) tag;

        Toast.makeText(MainActivity.this, "del " + id, Toast.LENGTH_SHORT).show();

        ContentResolver resolver = getContentResolver();
        int num = resolver.delete(
                ContactsContract.RawContacts.CONTENT_URI,
                ContactsContract.RawContacts.CONTACT_ID + "=?",
                new String[]{Long.toString(id)}
        );

        if (num > 0) {
            requeryCursor();
        }

    }


}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值