如何使用按钮单击复选框获取列表视图中的选定项目

时间:2013-12-13 16:45:44

标签: android listview checkbox contacts android-contacts

我正在尝试在列表视图中获取联系人,并在按钮单击时获取所选项目。我使用自定义适配器,但我不知道如何获取所选项目。

我尝试了很多不同的方法,比如setOnItemChangeListener来存储更改状态项。但没有人工作。

这是代码,

package com.example.callblocker;

import java.util.ArrayList;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Checkable;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.Toast;

/**
 * Developed by Azharahmed
 */
public class MainActivity extends ListActivity {
    /** Called when the activity is first created. */

    private ArrayList<Contact> contact_list = null;
    private ProgressDialog mProgressDialog = null;
    private contactAdapter mContactAdapter = null;
    private Runnable mViewcontacts = null;

    private ArrayList<Contact> items;
    boolean[] isChecked;
    Cursor mCursor;
    ListView lv;
    Button blockSelectedBtn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        contact_list = new ArrayList<Contact>();
        lv = getListView();

        blockSelectedBtn = (Button)findViewById(R.id.button1);
        blockSelectedBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                for (int i = 0; i < mContactAdapter.getCount(); i++)
                {
                    Contact contact = mContactAdapter.getItem(i);
                    if (((Checkable) contact).isChecked())
                    {
                        Toast.makeText(MainActivity.this,
                                contact.getContactName() + " is Checked!!",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

        mViewcontacts = new Runnable() {
            @Override
            public void run() {
                getContacts();
            }
        };

        Thread thread = new Thread(null, mViewcontacts, "ContactReadBackground");
        thread.start();
        mProgressDialog = ProgressDialog.show(MainActivity.this,
                "Please Wait...", "Retriving Contacts...", true);
    }

    @SuppressWarnings("unused")
    private void getContacts() {

        try {

            String[] projection = new String[] {
                    ContactsContract.Contacts.DISPLAY_NAME,
                    ContactsContract.Contacts.HAS_PHONE_NUMBER,
                    ContactsContract.Contacts._ID };

            mCursor = managedQuery(ContactsContract.Contacts.CONTENT_URI,
                    projection, ContactsContract.Contacts.HAS_PHONE_NUMBER
                            + "=?", new String[] { "1" },
                    ContactsContract.Contacts.DISPLAY_NAME);

            while (mCursor.moveToNext()) {
                Contact contact = new Contact();

                String contactId = mCursor.getString(mCursor
                        .getColumnIndex(ContactsContract.Contacts._ID));
                contact.setContactName(mCursor.getString(mCursor
                        .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
                contact_list.add(contact);
            }
            isChecked = new boolean[mCursor.getCount()];

            for (int i = 0; i < isChecked.length; i++) {
                isChecked[i] = false;
            }

            this.mContactAdapter = new contactAdapter(this, R.layout.listview,
                    contact_list);
            lv.setAdapter(this.mContactAdapter);
            mCursor.close();

            runOnUiThread(returnRes);

        } catch (Exception e) {
            Log.d("getContacts", e.getMessage());
        }
    }

    public class contactAdapter extends ArrayAdapter<Contact> {

        public contactAdapter(Context context, int textViewResourceId,
                ArrayList<Contact> items1) {
            super(context, textViewResourceId, items1);
            items = items1;
        }

        @Override
        public View getView(final int position, View convertView,
                ViewGroup parent) {
            ViewHolder mViewHolder;

            mViewHolder = new ViewHolder();
            LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = vi.inflate(R.layout.listview, parent, false);
            mViewHolder.cb = (CheckBox) convertView.findViewById(R.id.checkBox);
            mViewHolder.cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    Toast.makeText(MainActivity.this, "item changed", Toast.LENGTH_LONG).show();

                }
            });
            convertView.setTag(mViewHolder);

            if (isChecked[position] == true)
                mViewHolder.cb.setChecked(true);
            else
                mViewHolder.cb.setChecked(false);
            mViewHolder.cb
                    .setOnCheckedChangeListener(new OnCheckedChangeListener() {

                        @Override
                        public void onCheckedChanged(CompoundButton buttonView,
                                boolean ischecked) {
                            if (buttonView.isChecked()) {
                                isChecked[position] = true;
                            } else {
                                isChecked[position] = false;
                            }
                        }
                    });

            Contact contacts = items.get(position);
            if (contacts != null) {
                if (mViewHolder.cb != null) {
                    mViewHolder.cb.setText(contacts.getContactName());
                }
            }

            return convertView;
        }
    }

    public class ViewHolder {
        CheckBox cb;
    }

    private Runnable returnRes = new Runnable() {

        @Override
        public void run() {
            if (mProgressDialog.isShowing())
                mProgressDialog.dismiss();
            mContactAdapter.notifyDataSetChanged();
        }
    };

   }

这是错误代码之一。

    12-13 16:36:02.407: E/AndroidRuntime(14885): FATAL EXCEPTION: main
12-13 16:36:02.407: E/AndroidRuntime(14885): java.lang.ClassCastException: com.example.callblocker.Contact
12-13 16:36:02.407: E/AndroidRuntime(14885):    at com.example.callblocker.MainActivity$2.onClick(MainActivity.java:62)
12-13 16:36:02.407: E/AndroidRuntime(14885):    at android.view.View.performClick(View.java:2552)
12-13 16:36:02.407: E/AndroidRuntime(14885):    at android.view.View$PerformClick.run(View.java:9229)
12-13 16:36:02.407: E/AndroidRuntime(14885):    at android.os.Handler.handleCallback(Handler.java:587)
12-13 16:36:02.407: E/AndroidRuntime(14885):    at android.os.Handler.dispatchMessage(Handler.java:92)
12-13 16:36:02.407: E/AndroidRuntime(14885):    at android.os.Looper.loop(Looper.java:130)
12-13 16:36:02.407: E/AndroidRuntime(14885):    at android.app.ActivityThread.main(ActivityThread.java:3701)
12-13 16:36:02.407: E/AndroidRuntime(14885):    at java.lang.reflect.Method.invokeNative(Native Method)
12-13 16:36:02.407: E/AndroidRuntime(14885):    at java.lang.reflect.Method.invoke(Method.java:507)
12-13 16:36:02.407: E/AndroidRuntime(14885):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
12-13 16:36:02.407: E/AndroidRuntime(14885):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
12-13 16:36:02.407: E/AndroidRuntime(14885):    at dalvik.system.NativeStart.main(Native Method)

任何提示或建议都会非常有用。

2 个答案:

答案 0 :(得分:1)

我不知道很多droid编程,但通常要记录用户的这些信息,你想要设置一个动作监听器,然后为每个动作日志保存数据。 要编写动作侦听器,请按照以下步骤操作:

声明一个事件处理程序类,并指定该类实现ActionListener接口或扩展实现ActionListener接口的类。例如: public class MyClass实现ActionListener { 将事件处理程序类的实例注册为一个或多个组件上的侦听器。例如: someComponent.addActionListener(instanceOfMyClass); 包含在侦听器接口中实现方法的代码。例如: public void actionPerformed(ActionEvent e){     ... //对动作做出反应的代码...... }

这是一个如何做到这一点 - tutorial

答案 1 :(得分:0)

您可以尝试使用SparseBooleanArray获取所选项目(从位置)。 类似的stackoverflow问题及相关答案:

  1. How to get Selected items from Multi Select List View
  2. How to get all checked items from a ListView?