我正在设计应用程序,我希望允许用户选择多个联系人来发送消息。我已经使用以下代码成功检索了带有复选框的列表视图中的用户列表。现在我希望当用户单击“完成”按钮时,应在 EDITTEXT中检索所有选定联系人的电话号码,格式为John <+919898xxxxxx>、Rick <+919988xxxxxx>以及所有包含的电话号码只有 10 位数字,即“9898xxxxxx”应该自动存储在一个用逗号分隔的字符串中(9898xxxxxx,9988xxxxxx)。我怎样才能完成要求。
public class ContactsActivity extends ListActivity {
protected static final String TAG = null;
public String[] Contacts = {};
public int[] to = {};
public ListView myListView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
final Button done_Button = (Button) findViewById(R.id.done_Button);
final Button clear_Button =(Button) findViewById(R.id.clear_Button);
Cursor mCursor = getContacts();
startManagingCursor(mCursor);
ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, mCursor,
Contacts = new String[] {ContactsContract.Contacts.DISPLAY_NAME },
to = new int[] { android.R.id.text1 });
setListAdapter(adapter);
myListView = getListView();
myListView.setItemsCanFocus(false);
myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
clear_Button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Selections Cleared", Toast.LENGTH_SHORT).show();
ClearSelections();
}
});
/** When 'Done' Button Pushed: **/
done_Button.setOnClickListener(new View.OnClickListener() {
public void onClick (View v){
Log.i(TAG,":Done Button Selected:");
SparseBooleanArray selectedPositions = myListView.getCheckedItemPositions();
Log.i(TAG,"Number of Checked Positions: " + selectedPositions.size());
for (int i=0; i<selectedPositions.size(); i++) {
if (selectedPositions.get(selectedPositions.keyAt(i)) == true) {
//do stuff
}
}
}
});
}
private void ClearSelections() {
int count = this.myListView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
this.myListView.setItemChecked(i, false);
}
}
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.HAS_PHONE_NUMBER + " = '"
+ ("1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs,
sortOrder);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_contacts, menu);
return true;
}
}