1

我正在尝试创建一个联系人列表,每个联系人旁边都有一个复选框。我找到了一个对我有很大帮助的代码,但我仍然无法让它工作。这里是:

    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.SparseBooleanArray;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.view.View.OnClickListener;
    import android.widget.ArrayAdapter;
    import android.widget.CheckBox;
    import android.widget.Toast;

    public class ContactReadActivity extends ListActivity {
    private ArrayList<Contact> contacts = null;
    private ProgressDialog progressDialog = null;
    private ContactAdapter contactAdapter = null;
    private Runnable viewContacts = null;
    private SparseBooleanArray selectedContacts =   new SparseBooleanArray()  ; 

    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main2);
            contacts = new ArrayList<Contact>();
            this.contactAdapter = new ContactAdapter(this, R.layout.read_contacts, contacts);
            setListAdapter(this.contactAdapter);

            viewContacts = new Runnable(){
                @Override
                public void run() {
                    getContacts();
                }
            };
            Thread thread =  new Thread(null, viewContacts, "ContactReadBackground");
            thread.start();
            progressDialog = ProgressDialog.show(ContactReadActivity.this,"Please wait...", "Retrieving contacts ...", true);



        }

        private void getContacts(){
            try{

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

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


                contacts = new ArrayList<Contact>();

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


                    String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));


                    contact.setContactName(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));

                    contacts.add(contact);



                }
                cursor.close();



              runOnUiThread(returnRes);
          }
            catch(Exception e){
                e.printStackTrace();
            }
        }

        private Runnable returnRes = new Runnable() {

            @Override
            public void run() {
            // close the progress dialog
            if (progressDialog.isShowing())
            progressDialog.dismiss();

            contactAdapter.notifyDataSetChanged();
            }
            };

        public class ContactAdapter extends ArrayAdapter<Contact> {

            private ArrayList<Contact> items;

            public ContactAdapter(Context context, int textViewResourceId, ArrayList<Contact> items) {
                    super(context, textViewResourceId, items);
                    this.items = items;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                    View view = convertView;
                    if (view == null) {
                        LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        view = vi.inflate(R.layout.read_contacts, null);
                    }
                    Contact contact = items.get(position);
                    if (contact != null) {
                            CheckBox nameCheckBox = (CheckBox) view.findViewById(R.id.checkBox);


                            nameCheckBox.setChecked(selectedContacts.get(position));


                            if (nameCheckBox != null) {
                                nameCheckBox.setText(contact.getContactName());
                            }

                            nameCheckBox.setOnClickListener(new OnItemClickListener(position,nameCheckBox.getText(),nameCheckBox));
                    }

                    return view;
            }

        }

        class OnItemClickListener implements OnClickListener{          
            private int position;
            private CharSequence text;
            private CheckBox checkBox;
            OnItemClickListener(int position, CharSequence text,CheckBox checkBox){
                    this.position = position;
                    this.text = text;
                    this.checkBox = checkBox;
            }
            @Override
            public void onClick(View arg0) {

                selectedContacts.append(position, true);


                Toast.makeText(getBaseContext(), "Clicked "+position +" and text "+text,Toast.LENGTH_SHORT).show();


            }              
        }

        public class Contact {
            private String contactName;

            public String getContactName() {
                return contactName;
            }
            public void setContactName(String contactName) {
                this.contactName = contactName;
            }


        }
    }

我有两个 XML 文件:

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


    <ListView
    android:id="@+id/android:list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"


    />


    </LinearLayout> 

和:

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

            <CheckBox android:text=""
                android:id="@+id/checkBox"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="25sp"/>
    </RelativeLayout>

当然我得到了清单中的许可

<uses-permission android:name="android.permission.READ_CONTACTS"/>

谁能告诉我我做错了什么?

谢谢!!

4

2 回答 2

1

尝试使用 ASyncTask 并简化您的实现..

活动

public class YourListActivity extends ListActivity {  

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

        // DoStuff

        ListView lv = getListView();
        new LoadContacts().execute();

        // DoStuff
    }    
}

异步任务

class LoadContacts extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Do Dialog stuff here
        }

        protected String doInBackground(String... args) {
            // Put your implementation to retrieve contacts here
            getContacts();
        }

        protected void onPostExecute(String file_url) {
            // Dismiss Dialog
            runOnUiThread(new Runnable() {
                public void run() {
                    // Create list adapter and notify it                    
                }
            });

        }

}
于 2012-06-26T08:59:12.160 回答
0

代码对我来说似乎很好。我对 ArrayAdapter 不太满意,我更喜欢使用 SimpleAdapter。在阅读了您的目的之后,我认为使用一个简单的适配器似乎很容易实现。这是一个简单的启动。

更多关于 ListView,我认为最好的,总是帮了我很多: http ://www.vogella.com/articles/AndroidListView/article.html

还有更多关于 SimpleAdapter,它真的很简单: http ://wptrafficanalyzer.in/blog/listview-with-images-and-text-using-simple-adapter-in-android/

于 2012-06-23T15:42:36.570 回答