使用复选框筛选联系人并获取电话号码。

4
我正在开发一个类似于所有Android手机上默认文本消息应用程序的应用。 我的问题是选择多个用户发送短信。 我已经将我的联系人存储为带有复选框的列表视图项目。现在我只需要从选定的联系人中获取电话号码。
我遇到的问题: 1)从我的列表视图中显示的联系人中获取电话号码 2)在新活动的textview中显示该号码
抱歉,如果我的代码难以理解,请问需要澄清。
以下是显示列表视图的XML文件contact_manager.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"
        android:orientation="vertical" >

        <ListView
            android:id="@+id/contactList"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />

        <Button
            android:id="@+id/showInvisible"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/showInvisible" />

    </LinearLayout>

这是我的活动,将一切调用在一起。

public final class ContactManager extends Activity {

public static final String TAG = "ContactManager";

private ListView mContactList;
private boolean mShowInvisible;
private Button mShowInvisibleControl;

/**
 * Called when the activity is first created. Responsible for initializing
 * the UI.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    Log.v(TAG, "Activity State: onCreate()");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.contact_manager);

    // Obtain handles to UI objects

    mContactList = (ListView) findViewById(R.id.contactList);
    mShowInvisibleControl = (Button) findViewById(R.id.showInvisible);

    // Initialize class properties
    mShowInvisible = false;
    // mShowInvisibleControl.setChecked(mShowInvisible);
    mShowInvisibleControl.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {

        }
    });
    populateContactList();
}

/**
 * Populate the contact list based on account currently selected in the
 * account spinner.
 */
private void populateContactList() {
    // Build adapter with contact entries
    Cursor cursor = getContacts();
    String[] fields = new String[] { ContactsContract.Data.DISPLAY_NAME };
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
            R.layout.contact_entry, cursor, fields,
            new int[] { R.id.contactEntryText });
    mContactList.setAdapter(adapter);
}

/**
 * Obtains the contact list for the currently selected account.
 * 
 * @return A cursor for for accessing the contact list.
 */
private Cursor getContacts() {
    // Run query
    Uri uri = ContactsContract.Contacts.CONTENT_URI;
    String[] projection = new String[] { ContactsContract.Contacts._ID,
            ContactsContract.Contacts.DISPLAY_NAME };
    String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
            + (mShowInvisible ? "0" : "1") + "'";
    String[] selectionArgs = null;
    String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
            + " COLLATE LOCALIZED ASC";

    return managedQuery(uri, projection, selection, selectionArgs,
            sortOrder);
}

contact_entry.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" >

    <CheckBox
        android:id="@+id/contactEntryText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@+id/contactEntryText" />

</LinearLayout>

<?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"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/contactList"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <Button
        android:id="@+id/showInvisible"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/showInvisible" />

</LinearLayout>

这是我的invite_text.xml文件。实际上,我想要在这个文本视图中输入号码,以便可以发送群发短信。
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/contacts"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:gravity="center"
                android:paddingBottom="10dp"
                android:paddingLeft="10dp"
                android:paddingTop="10dp"
                android:text="@string/contacts"
                android:textAppearance="?android:attr/textAppearanceLarge" />
            <!-- android:textColor="#fff" android:background="@drawable/header" for header background -->

            <Button
                android:id="@+id/contactsButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_alignParentTop="true"
                android:text="@string/contacts" />
        </RelativeLayout>

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/enter_contact"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <AutoCompleteTextView
            android:id="@+id/contactnumber"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="@string/to" >

            <requestFocus />
        </AutoCompleteTextView>

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/message_to_send"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/invite_text"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/message_join" />

        <Button
            android:id="@+id/sendtxt"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:onClick="doLaunchContactPicker"
            android:text="@string/send_txt" />
    </LinearLayout>

</ScrollView>

如果您需要我发布更多信息,请告知。

仍然没有解决这个问题 :( - The Tokenizer
你好,请上传 contact_entry.xml 布局文件。 - user517491
我关于问题的 .xml 代码已经发布,请在此处发布更多问题。 - The Tokenizer
6个回答

2
我没有查看你的代码,但以下是对我有效的机制:
1. 将 `setOnCheckedChangeListener` 放到你的复选框上。 2. 如果复选框被选中,则将该联系人添加到 `arraylist` 中。 3. 如果复选框未被选中,则从 `arraylist` 中删除该联系人。 4. 使用 `startActivityForResult()` 启动你的联系人列表活动,并覆盖 `onActivityResult()`。 5. 在“离开联系人活动”之前,在意图中设置您的“已选择联系人”。 6. 在你的活动中接收所选联系人。 7. 现在你有了已选择的联系人,你可以在 `TextView` 中显示它们。
注意:你需要使用自定义列表适配器:
自定义列表适配器:
public class YourAdapterName extends BaseAdapter{

private Context mContext;
private ArrayList<string> mValuestoShow;

/**
 * Constructor to be called to initialize adapter with values.
 * @param context
 * @param vector
 */
public YourAdapterName(Context context, ArrayList<string> contacts){
    mContext = context;
    mValuestoShow = contacts;
}

public int getCount() {
    if(null != mValuestoShow){
        return mValuestoShow.size();
    }
    return 0;
}

public Object getItem(int position) {
    if(position < mValuestoShow.size())
        return  mValuestoShow.get(position);
    else
        return null;
}

public long getItemId(int position) {
    return 0;
}

/**
 * This method can be override to enable/disable particular list row.
 */
@Override
public boolean isEnabled(int position) {
    //Write your code here......
    return super.isEnabled(position);
}

public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            LayoutInflater li =(LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = li.inflate(R.layout.contact_list_layout, null);
            holder = new ViewHolder();
            holder.name = (TextView)convertView.findViewById(R.id.name);
            holder.checkbox = (CheckBox)convertView.findViewById(R.id.checkbox);
            convertView.setTag(holder);
        }
        else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.name.setText(text goes here ....);

        holder.checkbox.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if ( isChecked )
                    //Add contact...
                else
                    //Remove contact.
            }
        });

        return convertView;
    }

    class ViewHolder {
        TextView name;
        CheckBox checkbox;
    }

}

your_layout.xml

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

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="50dp"
        android:ellipsize="end"
        android:singleLine="true"
        android:textColor="@android:color/black" />

    <CheckBox
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true" />

</RelativeLayout>

有没有人有一个项目的压缩包可以分享一下?我还是新手,正在尝试做同样的事情(让用户选择联系人,然后在调用活动中获取所选列表)。分散的代码有点让我感到不知所措。同时也@jeet。 - learner

1
请按照以下步骤使其正常工作:

->创建一个布尔数组,大小等于光标。该数组将表示联系人的选中状态。 ->在xml中使复选框不可点击和无法聚焦。 ->在ListVIew上设置setOnItemClickListener,并在onItemClick方法中切换位置上的布尔数组的值,以选择项目。 ->在按钮上设置OnClickListener,并在侦听器的onClick方法中通过以下方式从光标中获取数字:

ArrayList<String> numbers=new ArrayList<String>();
cursor.moveToFirst();
for(int i=0;i<cursor.getCount;i++)
{
     cursor.moveToNext();
     if(selected[i])
     {
           //fetch contact from cursor
           //add number to numbers
     }
}

//使用ArrayList numbers发送联系人,似乎无法将多个号码附加到同一条消息中。在这种情况下,通过循环向号码发送消息,请参见以下主题: 在Android中向多个人发送短信在Android中使用SMSManager无法发送短信


1

有没有人有一个项目的压缩包可以分享一下?我还是新手,正在尝试做同样的事情(让用户选择联系人,然后在调用活动中获取所选列表)。分散的代码有点让我无从下手。同时也@SimoneCasagranda(我找不到你项目的压缩包)。 - learner

0

我认为下面的代码将会得到你期望的结果... 你的主类将会像下面这样...

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

public class GetSelectedContacts extends Activity{
    int CONTACTS_REQUEST_CODE =1;
    Activity thisActivity;
    ArrayList<String> selectedConatcts;
    LinearLayout contactdisp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        thisActivity = this;
        Button btn = (Button)findViewById(R.id.btn_selectContact);
        contactdisp = (LinearLayout)findViewById(R.id.lnr_contactshow);
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(thisActivity,ListActivitySampleActivity.class);
                startActivityForResult(intent, CONTACTS_REQUEST_CODE);
            }
        });


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data!=null){
            Bundle bundle = data.getExtras();
            if(requestCode ==1){
                selectedConatcts = bundle.getStringArrayList("sel_contacts");
                Log.v("", "Selected contacts-->"+selectedConatcts);
                if(selectedConatcts.size()<0){

                }else{
                    for(int i =0;i<selectedConatcts.size();i++){
                        LinearLayout lnr_inflate = (LinearLayout)View.inflate(thisActivity, R.layout.contacts_inflate, null);
                        EditText edt = (EditText)lnr_inflate.findViewById(R.id.edt_contact);
                        edt.setText(selectedConatcts.get(i));
                        contactdisp.addView(lnr_inflate);
                    }

                }
            }
        }
    }
}

类似于联系人选择的类

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class ListActivitySampleActivity extends Activity {
    static ContentResolver cr;
    String[] phone_nos;
    ArrayList<String> selectedContacts = new ArrayList<String>();
    Activity thisActivity;
    Button btn;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);
        thisActivity = this;
        final ListView lst = (ListView)findViewById(R.id.listView1);
        populateContact();
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(thisActivity, android.R.layout.simple_list_item_multiple_choice, phone_nos);
        lst.setAdapter(adapter);
        lst.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        lst.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {

            }
        });
        final int len = lst.getCount();
        final SparseBooleanArray checked = lst.getCheckedItemPositions();


        btn = (Button)findViewById(R.id.btn_send);
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {       
                 for (int i = 0; i < len; i++)
                     if (checked.get(i)) {
                      selectedContacts.add(phone_nos[i]);
                       //you can you this array list to next activity
                      /* do whatever you want with the checked item */
                     }
                Bundle bundle = new Bundle();
                bundle.putStringArrayList("sel_contacts", selectedContacts);

                Intent contactIntent = new Intent();
                contactIntent.putExtras(bundle);
                setResult(1, contactIntent);
                thisActivity.finish();
//               Log.v("", "selected-->"+selectedContacts); 
            }
        });

    }
    private void populateContact(){
        Uri myContacts = ContactsContract.CommonDataKinds.Phone.CONTENT_URI ;
        Cursor mqCur =  managedQuery(myContacts, null, null, null, null);
        phone_nos = new String[mqCur.getCount()];
        int i =0;
        if(mqCur.moveToFirst())
        {              
            do
            {          
                String phone_no = mqCur.getString(mqCur
                        .getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
                phone_nos[i] = phone_no;
                i++;
            }

            while(mqCur.moveToNext());
        }
    }
}

那段代码与我想要做的类似。不过我需要提取那些信息并在一个 EditText 中显示出来。 - The Tokenizer
如果您需要我的 XML 文件,请与我联系。 - Satheeshkumar
Satheesh,你能否上传你的XML文件呢? - dythe
有没有人有一个项目的压缩包可以分享一下?我还是新手,正在尝试做同样的事情(让用户选择联系人,然后在调用活动中获取所选列表)。分散的代码让我有点不知所措。 - learner

0

我建议你看一下我上个月写的教程,link,以管理列表中复选框的选择(它可以帮助你保持状态并通过ID检索项目)。

我认为最好通过ID来管理列表,但向用户显示联系人姓名。之后,您可以传递您的ID,并使用Jeet告诉您的机制将它们发送出去。


0

我只是要发布一个策略回答。在列表适配器中使用哈希映射。使用一个不显示的键来存储要拨打的电话号码。允许在列表视图中进行多项选择。使用所选条目中存储的电话号码。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接