AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="example.autoform"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="15" />    <application        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name=".RegistrationActivity"            android:label="@string/title_activity_main" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application><uses-permission android:name="android.permission.READ_CONTACTS"/></manifest>

create class Contact.class

package example.autoform;public class Contact {    public String phone = "";    public String firstName = "";    public String lastName = "";    public String email = "";    public String id = "";    @Override    public String toString(){        return firstName + " " + lastName + " " + phone + " " + email;    }}

create classContactManager:

public class ContactManager {   //use ContentResolver to queryprivate final ContentResolver resolver;    public ContactManager(ContentResolver cr){        resolver = cr;    }    public Contact getContact(Contact partial){    Contact contact=new Contact();    contact.id=partial.id;    contact.phone=partial.phone;    String[] projection=new String[]{    StructuredName.GIVEN_NAME,    StructuredName.FAMILY_NAME,    StructuredName.RAW_CONTACT_ID,    StructuredName.CONTACT_ID    };    String selection=StructuredName.CONTACT_ID+"? AND"+Data.MIMETYPE+"='"+StructuredName.CONTENT_ITEM_TYPE+"'";    String[] selectionArgs=new String[]{contact.id};    Cursor nameCursor=null;    try{    nameCursor=resolver.query(Data.CONTENT_URI, projection, selection, selectionArgs, null);    if(nameCursor.moveToFirst()){    contact.firstName=nameCursor.getString(nameCursor.getColumnIndex(StructuredName.GIVEN_NAME));    contact.lastName=nameCursor.getString(nameCursor.getColumnIndex(StructuredName.FAMILY_NAME));    }    }finally{    if(nameCursor!=null){    nameCursor.close();    }    }    projection=new String[]{Email.DATA1,Email.CONTACT_ID};    selection=Email.CONTACT_ID+"=?";    Cursor emailCursor=null;    try{    emailCursor=resolver.query(Email.CONTENT_URI, projection, selection, selectionArgs, null);    if(emailCursor.moveToFirst()){    contact.email=emailCursor.getString(emailCursor.getColumnIndex(Email.DATA1));    }    }finally{    if(emailCursor!=null)    emailCursor.close();    }    return contact;    }        public ArrayList<Contact> findByPhoneSubString(String phoneSubStr){    ArrayList<Contact> contacts=new ArrayList<Contact>();    String[] projection={Phone.CONTACT_ID,Phone.NUMBER};    String selection=Data.IN_VISIBLE_GROUP+"=1 AND"+Phone.NUMBER+"LIKE?";    String[] selectionArgs={"%"+phoneSubStr+"%"};    if(phoneSubStr==null){    selection=null;    selectionArgs=null;    }    Cursor phoneCursor=null;    try{    //execute    phoneCursor=resolver.query(Phone.CONTENT_URI, projection, selection, selectionArgs, null);    int idCol=phoneCursor.getColumnIndex(Phone.CONTACT_ID);    int numCol=phoneCursor.getColumnIndex(Phone.NUMBER);    //iterate over result set    while(phoneCursor.moveToNext()){    long id=phoneCursor.getLong(idCol);    String phoneNum=phoneCursor.getString(numCol);    Contact contact=new Contact();    contact.id=String.valueOf(id);    contact.phone=phoneNum;    contacts.add(contact);    }        }finally{    if(phoneCursor!=null)    phoneCursor.close();    }        return contacts;    }}

create activity classRegistrationActivity:

public class RegistrationActivity extends Activity { TextView first; TextView last; TextView email; AutoCompleteTextView phone;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                first = (TextView)findViewById(R.id.entry_first_name);        last = (TextView)findViewById(R.id.entry_last_name);        email = (TextView)findViewById(R.id.entry_email);        phone = (AutoCompleteTextView)findViewById(R.id.entry_phone);        phone.addTextChangedListener(new TextWatcher(){@Overridepublic void afterTextChanged(Editable textInput) {// TODO Auto-generated method stub}@Overridepublic void beforeTextChanged(CharSequence s, int start, int count,int after) {// TODO Auto-generated method stub}@Overridepublic void onTextChanged(CharSequence s, int start, int before,int count) {// TODO Auto-generated method stubif(s.length()==2){PhoneLookupTask task=new PhoneLookupTask();task.execute(s.toString());}}         });        email.setOnEditorActionListener(new OnEditorActionListener(){@Overridepublic boolean onEditorAction(TextView v, int actionId,KeyEvent event) {// TODO Auto-generated method stubsubmitForm();return true;}                });        Button doneButton = (Button)this.findViewById(R.id.done);        doneButton.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v) {// TODO Auto-generated method stubsubmitForm();}                });          }    class PhoneLookupTask extends AsyncTask<String,Void,ArrayList<Contact>>{    Context context=RegistrationActivity.this;@Overrideprotected ArrayList<Contact> doInBackground(String... args) {ContactManager mgr=new ContactManager(context.getContentResolver());if(args.length==0){return mgr.findByPhoneSubString(null);}return mgr.findByPhoneSubString(args[0]);}protected void onPostExecute(ArrayList<Contact> result){final HashMap<String,Contact> phoneMap=new HashMap<String,Contact>();final String[] phonesList=new String[result.size()];for(int i=0;i<result.size();i++){Contact oc=result.get(i);phonesList[i]=removeFormat(oc.phone);phoneMap.put(removeFormat(oc.phone), oc);}ArrayAdapter<String> phoneAdapter=new ArrayAdapter<String>(context,R.layout.phone_suggest,phonesList);phone.setAdapter(phoneAdapter);phone.setOnItemClickListener(new OnItemClickListener(){@Overridepublic void onItemClick(AdapterView<?> autoCompleteView, View view,int position, long id) {// TODO Auto-generated method stubString phoneNum=(String)autoCompleteView.getItemAtPosition(position);Contact contact=phoneMap.get(phoneNum);if(contact!=null){ContactDetailLookupTask task=new ContactDetailLookupTask();task.execute(contact);}}});}    }        protected void submitForm(){        InputMethodManager mgr=(InputMethodManager)this.getSystemService(INPUT_METHOD_SERVICE);    mgr.hideSoftInputFromInputMethod(first.getApplicationWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);    Contact contact=new Contact();    contact.firstName=first.getText().toString();    contact.lastName=last.getText().toString();    contact.email=email.getText().toString();    contact.phone=phone.getText().toString();    Toast.makeText(this, "Contact submited"+contact, Toast.LENGTH_LONG).show();    Handler h=new Handler();    h.postDelayed(new Runnable(){@Overridepublic void run() {// TODO Auto-generated method stubfinish();}        }, 5000L);    }        static String removeFormat(String phone){if(phone==null){return null;}StringBuffer num=new StringBuffer();for(char ch:phone.toCharArray()){num.append(ch);}return num.toString();        }        class ContactDetailLookupTask extends AsyncTask<Contact,Void,Contact>{@Overrideprotected Contact doInBackground(Contact... params) {// TODO Auto-generated method stubContactManager mgr=new ContactManager(getContentResolver());return mgr.getContact(params[0]);}protected void onPostExecute(Contact contact){  if (contact == null){                return;            }            if (!TextUtils.isEmpty(contact.firstName)) {                first.setText(contact.firstName);            } else {                first.setText("");            }            if (!TextUtils.isEmpty(contact.lastName)) {                last.setText(contact.lastName);            } else {                last.setText("");            }            if (!TextUtils.isEmpty(contact.email)) {                email.setText(contact.email);            } else {                email.setText("");            }}        }}

use this ContentProvider to get the list of phone numbersfor the AutoCompleteTextView

You can check theandroid.os.Build.VERSION at runtime to determine what version of the OSis running on the user’s phone, and pick the appropriate provider.

Android 3.0, a new constant was added to ContactsContract.CommonDataKinds.Email: ADDRESS. Its value is the same as Email.DATA1


valuse\colors.xml

<?xml version="1.0" encoding="utf-8"?><resources>  <color name="app_background">#dee6ed</color>  <color name="header">#6f7bb0</color>  <color name="subheader">#b2bcdf</color>  <color name="module_background">#f8f8f9</color>  <color name="bubble_bg">#ffffff</color>  <color name="table_view_bg">#ffffff</color>  <color name="call_to_action">#f5f4b6</color>  <color name="background_selected">#848fcf</color>  <color name="white">#ffffff</color>  <color name="black">#000000</color>  <color name="dark_gray">#222222</color>  <color name="gray">#888888</color>  <color name="light_gray">#a8a8a8</color>  <color name="blue_text">#0000ff</color>  <color name="blue_title_text">#3d588a</color>  <color name="myinfo_edit_bg">#fffefdd9</color>  <color name="myinfo_card_border">#fff14b66</color>  <color name="photo_selected_border_color">#ffff7f24</color>  <color name="warming_up">#ffea8030</color>  <!--  Use android transparent to avoid a bug where background set to transparent shows an image instead:  Stack overflow here:http://stackoverflow.com/questions/3822123/weird-layout-problem-please-see-the-attached-image  -->  <color name="transparent">@android:color/transparent</color></resources>

valuse\strings.xml

<resources>    <string name="app_name">AutoForm</string>    <string name="hello_world">Hello world!</string>    <string name="menu_settings">Settings</string>    <string name="title_activity_main">MainActivity</string>     <string name="label_enter_your_info">      Enter your contact info to get started    </string>    <string name="label_first_name">First name</string>    <string name="label_phone_number">Your phone number</string>    <string name="label_last_name">Last</string>    <string name="label_email_address">Email address</string>    <string name="done">Done</string></resources>

layout\main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:background="@color/app_background"  android:orientation="vertical">  <TextView android:padding="10dp"    android:layout_height="wrap_content"    android:id="@+id/enter_info_prompt"    android:text="@string/label_enter_your_info"    android:layout_width="match_parent"    android:background="@color/header"    android:textColor="@color/white"    android:textStyle="bold"    android:textSize="15sp"  /><ScrollView android:layout_width="match_parent"  android:layout_height="match_parent"><LinearLayout android:layout_width="match_parent"  android:layout_height="match_parent"  android:background="@color/app_background"  android:orientation="vertical">   <LinearLayout android:orientation="vertical"    android:layout_height="wrap_content"    android:layout_width="match_parent"    android:paddingTop="5dp"    android:paddingLeft="10dp"    android:paddingRight="10dp">    <TextView android:layout_height="wrap_content"      android:textSize="15sp"      android:layout_width="wrap_content"      android:padding="5dp"      android:textColor="@color/dark_gray"      android:text="@string/label_phone_number"    />    <AutoCompleteTextView android:layout_height="wrap_content"      android:layout_width="match_parent"      android:id="@+id/entry_phone"      android:textStyle="bold"      android:inputType="phone"      android:imeOptions="actionNext"    />  </LinearLayout>   <LinearLayout    android:layout_height="wrap_content"    android:layout_width="match_parent">    <LinearLayout      android:paddingTop="5dp"      android:paddingLeft="10dp"      android:paddingRight="10dp"      android:layout_weight="1"      android:layout_height="wrap_content"      android:layout_width="match_parent"      android:orientation="vertical">      <TextView        android:layout_height="wrap_content"        android:textSize="15sp"        android:layout_width="wrap_content"        android:padding="5dp"        android:textColor="@color/dark_gray"        android:text="@string/label_first_name"/>      <EditText        android:layout_height="wrap_content"        android:layout_width="match_parent"        android:id="@+id/entry_first_name"        android:textStyle="bold"        android:capitalize="words"        android:imeOptions="actionNext"        android:inputType="textCapWords"        android:nextFocusDown="@+id/entry_last_name"        />    </LinearLayout>    <LinearLayout      android:paddingTop="5dp"      android:paddingLeft="10dp"      android:paddingRight="10dp"      android:layout_weight="1"      android:layout_height="wrap_content"      android:layout_width="match_parent"      android:orientation="vertical">      <TextView        android:layout_height="wrap_content"        android:textSize="15sp"        android:layout_width="wrap_content"        android:padding="5dp"        android:textColor="@color/dark_gray"        android:text="@string/label_last_name"/>      <EditText        android:layout_height="wrap_content"        android:layout_width="match_parent"        android:id="@+id/entry_last_name"        android:textStyle="bold"        android:capitalize="words"        android:inputType="textCapWords"        android:imeOptions="actionNext"                />            </LinearLayout>    </LinearLayout>  <LinearLayout    android:paddingTop="5dp"    android:paddingLeft="10dp"    android:paddingRight="10dp"    android:layout_height="wrap_content"    android:layout_width="match_parent"    android:orientation="vertical">    <TextView      android:layout_height="wrap_content"      android:textSize="15sp"      android:layout_width="wrap_content"      android:padding="5dp"      android:textColor="@color/dark_gray"      android:text="@string/label_email_address"/>    <EditText      android:layout_height="wrap_content"      android:layout_width="match_parent"      android:id="@+id/entry_email"      android:textStyle="bold"      android:inputType="textEmailAddress"      android:imeOptions="actionGo"      />  </LinearLayout>  <Button    android:layout_height="wrap_content"    android:layout_gravity="right"    android:layout_width="wrap_content"    android:id="@+id/done"    android:layout_margin="15dp"    android:textColor="@color/white"    android:text="@string/done"    android:minWidth="100dp"    android:textStyle="bold"    android:textSize="15sp"  /></LinearLayout></ScrollView>  </LinearLayout>

\layout\phone_suggest.xml

<?xml version="1.0" encoding="utf-8"?><TextView  xmlns:android="http://schemas.android.com/apk/res/android"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:textColor="@color/blue_text"  android:textSize="15dp"  ></TextView>


更多相关文章

  1. 代码中设置drawableleft
  2. android 3.0 隐藏 系统标题栏
  3. Android开发中activity切换动画的实现
  4. Android(安卓)学习 笔记_05. 文件下载
  5. Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
  6. 技术博客汇总
  7. android 2.3 wifi (一)
  8. AndRoid Notification的清空和修改
  9. Android中的Chronometer

随机推荐

  1. android canvas常用的方法解析(一)
  2. 隐形成本巨大 微软点评Android六宗罪
  3. Android应用程序私有目录下文件操作总结
  4. Android——贝塞尔曲线的水波浪效果实现
  5. Android中的动画和原理(帧动画和补间动画
  6. Android(安卓)RatingBar 评星控件的自定
  7. Android调用系统安装程序打开本地文件(包
  8. 初识Android(安卓)网络机顶盒开发
  9. 安卓开机logo和开机动画的几种实现方法
  10. Android之讯飞语音-文字转语音(不用另外安