我有一个edittext和一个按钮,我想在单击按钮时打开联系人详细信息,用户可以从中选择一个联系人。然后我需要将所选联系人的手机号码放在edittext中。我该怎么做?谢谢
问问题
1082 次
1 回答
3
这很简单。首先您需要创建编辑文本和按钮,然后编写以下代码:
private EditText e;
private static final String DEBUG_TAG = "InviteActivity";
private static final int CONTACT_PICKER_RESULT = 1001;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
e=(EditText)findViewById(R.id.editText1);
}
public void doLaunchContactPicker(View view)
{
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
}
@Override
protected void onActivityResult(int requestCode,int resultCode,Intent data)
{
if(resultCode==RESULT_OK)
{
switch(requestCode)
{
case CONTACT_PICKER_RESULT:
Cursor cursor=null;
String phone="";
try
{ Uri result=data.getData();
String id=result.getLastPathSegment();
cursor=getContentResolver().query(Phone.CONTENT_URI,null, Phone.CONTACT_ID +"=?",new String[] {id},null);
int phoneIdx=cursor.getColumnIndex(Phone.NUMBER);
if(cursor.moveToFirst())
{
phone=cursor.getString(phoneIdx);
}
if(phone.equals(""))
{
Toast.makeText(getBaseContext(),"There is no phone number for that contac", Toast.LENGTH_LONG).show();
}
else
{
e.setText(phone);
}
}
catch(Exception e)
{
Toast.makeText(getBaseContext(),"There is no phone number for that contact", Toast.LENGTH_SHORT).show();
}
finally
{
if(cursor!=null)
{
cursor.close();
}//finally
break;
}//switch
}//if
else {
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}//on activity result
}//class
对于 Button 属性,请给出:
android:onClick="doLaunchContactPicker"
不要忘记提供使用权限:
<uses-permission android:name="android.permission.READ_CONTACTS" />
如果这个答案有用请不要忘记接受..
于 2011-06-18T04:14:17.930 回答