使用checkBox联系列表,以选择组消息

时间:2014-03-04 12:59:49

标签: android android-contacts

我想使用复选框制作联系人列表。所以我必须选择联系人来发送群组消息;我试过这段代码,但它不起作用...... 您可以向我建议如何进一步获取联系人列表。

MainActivity.java

package com.example.cont1;

import java.util.ArrayList;

import com.example.cont.MainActivity;
import com.example.listo1.Demo;
import com.example.listo1.R;

import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.database.Cursor;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends ListActivity {
    StringBuilder sb= new StringBuilder();
    String str;
    ListView tx;
    private Contact selectedAdapter;
    private ArrayList<String> list;

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

    class ast extends AsyncTask<String, Void, String> {
        String name, phone;
        ProgressDialog pd;

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();

            pd = ProgressDialog.show(MainActivity.this, "", "loading");
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            pd.cancel();
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, str);
            setListAdapter(adapter);
            getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
            //textDetail.setText(sb);
        }

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub

            ContentResolver cr = getContentResolver();
            Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
            String phone = null;

            if (cur.getCount() > 0) {
                Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
                while (phones.moveToNext()) {
                    name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    phone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    sb.append("\n " + name + "\n" + phone);
                    sb.append("\n............................\n");
                    str=sb.toString();
                }

                phones.close();
            }

            return null;
        }
    }
}

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Toast.makeText(this, String.valueOf(getListView().getCheckedItemCount()), Toast.LENGTH_LONG).show();
        return true;
    }
} 

Contact.java

package com.example.cont1;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class Contact extends ArrayAdapter {
    private MainActivity list;
    // used to keep selected position in ListView
    private int selectedPos = -1;   // init value for not-selected
    private Context context;
    private String[] values;

    public Contact(Context context, String[] values) {
        super(context, R.layout.activity_main, values);
        this.context = context;
        this.values = values;
    }

    public void setSelectedPosition(int pos){
        selectedPos = pos;
        // inform the view of this change
        notifyDataSetChanged();
    }

    public int getSelectedPosition(){
         return selectedPos;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        LayoutInflater vi = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = vi.inflate(R.layout.activity_main, null);

        // get text view
        TextView label = (TextView)v.findViewById(R.id.textView1);
        ImageView btn=(ImageView)v.findViewById(R.id.icon);

        if (convertView == null) {            
            v = vi.inflate(R.layout.activity_main, parent, false);
        }
        else
            v = convertView;

        TextView text1 = (TextView) v.findViewById(R.id.textView1);
        text1.setText(values[position]);
        LinearLayout layout_item = (LinearLayout) v.findViewById(R.id.linear);
        //Set the background and text color
        if (position % 2 == 0) {
            layout_item.setBackgroundColor(context.getResources().getColor(R.color.black));
            text1.setTextColor(context.getResources().getColor(R.color.white));
        } else {
            layout_item.setBackgroundColor(context.getResources().getColor(R.color.white));
            text1.setTextColor(context.getResources().getColor(R.color.black));
        }    

        return v;
    }
}

activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <ScrollView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <LinearLayout
                android:id="@+id/linear"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <TextView
                    android:id="@+id/textView1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_alignParentTop="true"
                    android:layout_margin="10dp"/>

                <ImageView
                    android:id="@+id/icon"
                    android:layout_width="22px"
                    android:layout_height="22px"
                    android:layout_marginLeft="4px"
                    android:layout_marginRight="10px"
                    android:layout_marginTop="4px">
                </ImageView>
            </LinearLayout>
    </ScrollView>
</LinearLayout>

rowLayout.xml

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

    <ListView
        android:id="@+id/list"
        android:layout_height="match_parent"
        android:layout_width="match_parent"/>

</LinearLayout>

1 个答案:

答案 0 :(得分:0)

使用异步任务执行此操作似乎相当复杂,但这里有一个来自https://stackoverflow.com/a/17878191/2545832的Snippet,但是更完整(但仍然非常简单)正在运行(我测试过):

主要活动:

import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

    ListView lvCallList;
    ProgressDialog pd;
    ArrayList<String> aa = new ArrayList<String>();
    ArrayList<String> num= new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lvCallList = (ListView) findViewById(R.id.list);

        new AsyncTask<Void, Void, Void>() 
        {
            @Override
            protected void onPreExecute() 
            {
                pd = ProgressDialog.show(MainActivity.this,
                        "Loading..", "Please Wait", true, false);
            }// End of onPreExecute method

            @Override
            protected Void doInBackground(Void... params) 
            {
                getContacts();

                return null;
            }// End of doInBackground method

            @Override
            protected void onPostExecute(Void result)
            {
                pd.dismiss();
                CustomAdapter cus = new CustomAdapter(MainActivity.this);
               // ArrayAdapter<String>   arrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,aa);
             lvCallList.setAdapter(cus);

            }//End of onPostExecute method
        }.execute((Void[]) null);
    }
        private void getContacts()
        {
            ContentResolver cr = getContentResolver();
            Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,null, null, null);
            if (cur.getCount() > 0)
            {
                while (cur.moveToNext())
                {
                    String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                    String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

                    aa.add(name);
                    if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
                    {
                        Cursor pCur = cr.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                                null,
                                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", 
                                                new String[]{id}, 
                                                null);
                        while (pCur.moveToNext())
                        {
                            String phoneNumber = pCur.getString(pCur.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));
                            num.add(phoneNumber);
                        } 
                        pCur.close();
                    }
                }
            }
        }

        public class CustomAdapter extends BaseAdapter 
        {
            /*
             * Variables Declaration section
             */
            private Context mContext;

            public CustomAdapter(Context context) 
            {
                mContext = context;
            }//End of CustomAdapter constructor

            public int getCount() 
            {
                return aa.size();
            }//End of getCount method

            public Object getItem(int position) 
            {
                return position;
            }//End of getItem method

            public long getItemId(int position) 
            {
                return position;
            }//End of getItemId method

            public View getView(int position, View convertView, ViewGroup parent) 
            {
                ViewHolder holder;
                final int pos = position;

                if (convertView == null) 
                {
                    holder = new ViewHolder();

                    convertView = LayoutInflater.from(mContext).inflate(R.layout.display_contact, null);
                    holder.textviewName = (TextView) convertView.findViewById(R.id.textView1);
                    holder.textviewNumber = (TextView) convertView.findViewById(R.id.textView2);
                    holder.checkbox = (CheckBox) convertView.findViewById(R.id.checkBox1);

                    convertView.setTag(holder);
                }//End of if condition
                else
                {
                    holder = (ViewHolder) convertView.getTag();
                }//End of else

                holder.checkbox.setId(position);
                holder.textviewName.setId(position);
                holder.textviewNumber.setId(position);


                holder.textviewName.setText(aa.get(position));
                holder.textviewNumber.setText("No. "+num.get(position));

                holder.id = position;

                return convertView;
            }//End of getView method
        }//End of CustomAdapter instance inner class

        static class ViewHolder 
        {
            TextView textviewName;
            TextView textviewNumber;
            CheckBox checkbox;
            int id;
        }

}

activity_main.xml中

   <?xml version="1.0" encoding="utf-8"?>
    <ListView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent" 
        android:id="@+id/list">    

    </ListView>

display_contact.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView1"/>
    <TextView android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView2"/>
    <CheckBox android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/checkBox1"/>

</LinearLayout>

我在您的代码中看到您可以选择多个项目,因此从此列表中选择多个联系人一定不会有问题。你有两个选择:每个复选框上的监听器或列表上的长按监听器。

祝你好运:)