【问题标题】:using checkbox to filter contacts and get phone number使用复选框过滤联系人并获取电话号码
【发布时间】:2012-02-26 02:40:06
【问题描述】:

我正在开发一款与所有 Android 手机上的默认短信应用类似的应用。我的问题是选择多个用户向其发送 SMS 消息。到目前为止,我所做的是将我的联系人存储为带有复选框的列表视图项目。现在我只需要从选定的联系人中获取电话号码。

所以我在做什么时遇到了麻烦。 1)从我的列表视图中显示的联系人中提取电话号码 2)在新活动的文本视图中显示该数字

对不起,如果我的代码难以理解,请询问您是否需要澄清。

这是显示列表视图的 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>

如果您需要我发布更多信息,请询问。

【问题讨论】:

  • 还没有解决这个问题:(
  • 您好,请发布contact_entry.xml布局文件
  • 我的 .xml 代码已发布,如果您有更多问题,请在此处发布

标签: java android checkbox android-contacts


【解决方案1】:

我没有看过你的代码,但这里是对我有用的机制:

1.setOnCheckedChangeListener 放在您的复选框中。

2.如果CheckboxChecked,则将该联系人添加到arraylist

3. 如果CheckBoxunchecked,则从arraylist 中删除该联系人。

4. 使用startActivityForResult() 开始您的联系人列表活动并覆盖onActivityResult()

5.leaving contact activity 之前设置您的selected contacts in intent

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 也是如此。
【解决方案2】:

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

->有一个布尔数组,大小等于光标。该数组将表示已检查的接触状态。 -> 在 xml 中使复选框不可点击且不可聚焦。 -> setOnItemClickListener on ListVIew 和 onItemClick 方法在位置切换布尔数组的值,选中项目。 ->在Button上设置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号码发送Contact,好像不能在同一条消息中附加多个号码,如果是循环发送消息给号码,请看下面的帖子: Sending sms to multiple people in android AMD Unable to send sms using SMSManager in Android

【讨论】:

    【解决方案3】:

    您的问题没有确切的答案。您必须编写自己的适配器并支持多选。我已经回复了类似的问题(如果这有帮助,请告诉我,我可以详细解释):

    Android listview toggle button

    android : checkboxes in a ListView ( strange behaviour of selected element)

    【讨论】:

    • 有没有人有你不介意分享的项目的压缩包。我还是新手,我正在尝试做同样的事情(让用户选择联系人,然后在呼叫活动中获取所选列表)。分散的代码让我有点不知所措。标记:@SimoneCasagranda 以及(我找不到您项目的 zip)。
    【解决方案4】:

    我只是要发布一个策略答案。对列表适配器使用 hashmap。使用未显示的键存储要呼叫的电话号码。允许在列表视图中进行多项选择。使用所选条目中存储的电话号码。

    【讨论】:

      【解决方案5】:

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

      我认为如果您通过 id 管理列表但向用户显示联系人姓名会更好。之后,您可以传递您的 id 并使用 jeet 告诉您的机制发送它们。

      【讨论】:

        【解决方案6】:

        我认为下面的代码将给出你所期望的结果...... 你的主要课程会像下面这样...

        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
        • 如果您也需要我的 xml 文件,请与我联系。
        • Satheesh 也可以上传你的 xml 文件吗?
        • 有没有人有你不介意分享的项目的压缩包。我还是新手,我正在尝试做同样的事情(让用户选择联系人,然后在呼叫活动中获取所选列表)。分散的代码让我有点不知所措。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-26
        • 2015-11-10
        • 2015-06-01
        • 2015-01-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多