我正在制作恐慌应用,并允许用户添加多个联系人并通过点击添加到联系人按钮,无论何时他/她想要添加。
在EditText中获得如下内容:9867XXXXXX,9866XXXXXX,......
我需要的更改:
限制至 5个联系人仅
我知道如何限制EditText中的字符长度,但不知道如何限制5个联系人?
private Button btnAddContacts ;
private EditText editContacts
..............................
btnAddContacts = (Button) findViewById(R.id.btnAddContacts);
btnAddContacts.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent it= new Intent(Intent.ACTION_GET_CONTENT);
it.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(it, 1);
}
});
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
showSelectedNumber(type, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(int type, String number) {
if(editContacts != null && editContacts.getText().toString().length()==0)
editContacts.setText(number);
else
if(editContacts != null) editContacts.append(","+number);
}
答案 0 :(得分:1)
您可以使用标记maxNoContacts
段:
public YourActivity extends Activity
{
int maxNoContacts = 0;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState)
...
btnAddContacts.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(maxNoContacts <5 )
{
Intent it= new Intent(Intent.ACTION_GET_CONTENT);
it.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(it, 1);
}
else
{
//show toast saying you added maximum no of contacts.
}
}
});
}
//如果正确获取了联系人,则更新maxNoContacts。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
maxNoContacts++; //Increment maxNoContacts if it fetches contact properly.
showSelectedNumber(type, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
}