1. 程式人生 > >對手機聯絡人的一些操作

對手機聯絡人的一些操作

首先,我們建立佈局檔案


main的主體佈局

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/drawerlayout"
    >
    <LinearLayout
        android:id="@+id/center"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:background="@android:color/holo_blue_light"
            android:layout_width="match_parent"
            android:layout_height="60dp"></android.support.v7.widget.Toolbar>
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="onClick"
            android:text="點選新增一個聯絡人"/>
        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>

    </LinearLayout>

    <!--Fragment替換該位置-->
    <FrameLayout
        android:id="@+id/left_layout"
        android:layout_width="300dp"
        android:layout_height="match_parent"
        android:layout_gravity="left"></FrameLayout>
</android.support.v4.widget.DrawerLayout>

這是dialog的佈局檔案

<?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:orientation="vertical" >

    <EditText
        android:id="@+id/name_et"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </EditText>

    <EditText
        android:id="@+id/phone_et"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/email_et"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

這是fragment的佈局檔案

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_blue_light"
    >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="抽屜中過的Fragment"/>

</FrameLayout>


這是item佈局檔案

<?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="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/display_name_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:text="TextView"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/phone_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:text="TextView"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/email_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:text="TextView"
        android:textSize="18sp" />

</LinearLayout>

這是主體程式碼

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    private Toolbar mToolbar;
    private RecyclerView mRecyclerView;
    private DrawerLayout mDrawerLayout;
    private FragmentManager fm;
    private ContentResolver resolver;



    private ArrayList<PersonInfo> contacts = new ArrayList<PersonInfo>();
    private MyPhoneAdapter adapter;
    // raw_contacts 表的Uri
    private Uri rawContactsUri = ContactsContract.RawContacts.CONTENT_URI;
    // data 表的Uri
    private Uri dataUri = ContactsContract.Data.CONTENT_URI;
    // data表中的 phone 欄位
    private Uri phoneUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
    // data 表中的 email 欄位
    private Uri emailUri = ContactsContract.CommonDataKinds.Email.CONTENT_URI;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        initView();
        initPhoneLink();
    }
    //獲取手機聯絡人並展示在RecycleView中
    private void initPhoneLink() {
        resolver = getContentResolver();

        contacts.addAll(getContacts());
        Log.d("sxl", "initPhoneLink: "+contacts);

        adapter = new MyPhoneAdapter(contacts,MainActivity.this,mRecyclerView);
        mRecyclerView.setAdapter(adapter);

        // 點選 刪除 一條聯絡人資料
        adapter.setOnItemClickListener(new MyPhoneAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                int result = resolver.delete(rawContactsUri, "_id = ?",
                        new String[] { contacts.get(position).getRawId() });

                if (result > 0) {
                    contacts.remove(position);
                    adapter.notifyDataSetChanged();
                }
            }
        });
    }
    // 獲取聯絡人
    private ArrayList<PersonInfo> getContacts() {

        ArrayList<PersonInfo> list = new ArrayList<PersonInfo>();

        Cursor rawCursor = resolver.query(rawContactsUri, new String[] { "_id", "display_name" }, null, null, null);
        if (rawCursor != null) {
            while (rawCursor.moveToNext()) {
                // 用來儲存查詢到的結果值
                Map<String, String> map = new HashMap<String, String>();
                PersonInfo info = new PersonInfo();

                String rawId = rawCursor.getString(0);
                String display_name = rawCursor.getString(1);
                info.setRawId(rawId);
                info.setDisplay_name(display_name);
//                map.put("rawId", rawId);
//                map.put("display_name", display_name);

                // 根據 拿到的 rawId 查詢data 表中的資料
                // 獲取電話號碼
                Cursor phoneCursor = resolver.query(phoneUri, new String[] { "data1" }, "raw_contact_id = ?",
                        new String[] { rawId }, null);
                if (phoneCursor != null) {
                    while (phoneCursor.moveToNext()) {
                        String phone = phoneCursor.getString(0);
                        info.setPhone(phone);
//                        map.put("phone", phone);
                    }
                }

                phoneCursor.close();

                // 查詢 Email
                Cursor emailCursor = resolver.query(emailUri, new String[] { "data1" }, "raw_contact_id = ?",
                        new String[] { rawId }, null);
                if (emailCursor != null) {
                    while (emailCursor.moveToNext()) {
                        String email = emailCursor.getString(0);
                        info.setEmail(email);
//                        map.put("email", email);
                    }
                }

                emailCursor.close();
                // 一次迴圈 代表一個聯絡人
                list.add(info);
            }
            rawCursor.close();

        }
        return list;
    }

    public void onClick(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(R.mipmap.ic_launcher);
        builder.setTitle("警告");
        builder.setMessage("你確定要新增這個聯絡人嗎?");
        View dialogView = View.inflate(this, R.layout.dialog_layout, null);
        builder.setView(dialogView);

        final EditText name_et = (EditText) dialogView.findViewById(R.id.name_et);
        final EditText phone_et = (EditText) dialogView.findViewById(R.id.phone_et);
        final EditText email_et = (EditText) dialogView.findViewById(R.id.email_et);

        builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                String name = name_et.getText().toString();
                String phone = phone_et.getText().toString();
                String email = email_et.getText().toString();
                //新增聯絡人
                addContact(name, phone, email);
            }

        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.show();
    }

    // 新增聯絡人
    private void addContact(String name, String phone, String email) {

        // 先插入一條資料到 raw_contacts 表中 獲取者跳資料的 Id
        ContentValues values = new ContentValues();
        Uri uri = resolver.insert(rawContactsUri, values);
        long id = ContentUris.parseId(uri);

        // 插入name
        values.clear();
        values.put("raw_contact_id", id);
        values.put("data1", name);
        values.put("mimetype", "vnd.android.cursor.item/name");
        resolver.insert(dataUri, values);

        // 電話號碼
        values.clear();
        values.put("raw_contact_id", id);
        values.put("data1", phone);
        values.put("mimetype", "vnd.android.cursor.item/phone_v2");
        resolver.insert(dataUri, values);

        // email

        values.clear();
        values.put("raw_contact_id", id);
        values.put("data1", email);
        values.put("mimetype", "vnd.android.cursor.item/email_v2");
        resolver.insert(dataUri, values);

        // 重新整理一下
        contacts.clear();
        contacts.addAll(getContacts());
        adapter.notifyDataSetChanged();
    }


    private void initView() {

        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(manager);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
        //將fragment新增到佔位的位置
        fm = getSupportFragmentManager();
        fm.beginTransaction().replace(R.id.left_layout,new BlankFragment()).commit();
        //設定導航欄圖示
        mToolbar.setNavigationIcon(R.mipmap.ic_launcher);
        //設定導航欄圖示監聽
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDrawerLayout.openDrawer(Gravity.LEFT);
            }
        });
    }
}

這是BlankFragment的程式碼

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class BlankFragment extends Fragment {


    public BlankFragment() {
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_blank, container, false);
    }

}


這是MyPhoneAdapter的主體


import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;

/**
 * Created by 暖陽學長 on 2017/11/6.
 */

public class MyPhoneAdapter extends RecyclerView.Adapter<MyPhoneAdapter.ViewHolder> {
    private ArrayList<PersonInfo> mList;
    private Context mContext;
    private RecyclerView mRecyclerView;
    private LayoutInflater mInflater;

    public MyPhoneAdapter(ArrayList<PersonInfo> list, Context context, RecyclerView recyclerView) {
        mList = list;
        mContext = context;
        mRecyclerView = recyclerView;
        mInflater = LayoutInflater.from(mContext);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.item_layout,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        PersonInfo info = mList.get(position);
        holder.display_name_tv.setText(info.getDisplay_name());
        holder.email_tv.setText(info.getEmail());
        holder.phone_tv.setText(info.getPhone());
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mListener.onItemClick(view,position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }
    private OnItemClickListener mListener;
    public interface  OnItemClickListener{
        public void onItemClick(View view,int position);
    }
    public void setOnItemClickListener(OnItemClickListener mListener){
        this.mListener = mListener;
    }

    class ViewHolder extends RecyclerView.ViewHolder{
        TextView display_name_tv;
        TextView phone_tv;
        TextView email_tv;

        public ViewHolder(View itemView) {
            super(itemView);
            display_name_tv = (TextView) itemView.findViewById(R.id.display_name_tv);
            phone_tv = (TextView) itemView.findViewById(R.id.phone_tv);
            email_tv = (TextView) itemView.findViewById(R.id.email_tv);
        }
    }
}

這是PersonInfo的主體


public class PersonInfo {
    private String rawId;

    private String display_name;
    private String phone;
    private String email;

    public PersonInfo(String rawId, String display_name, String phone, String email) {
        this.rawId = rawId;
        this.display_name = display_name;
        this.phone = phone;
        this.email = email;
    }


    public PersonInfo() {
    }

    public String getRawId() {
        return rawId;
    }

    public void setRawId(String rawId) {
        this.rawId = rawId;
    }

    public String getDisplay_name() {
        return display_name;
    }

    public void setDisplay_name(String display_name) {
        this.display_name = display_name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }


    @Override
    public String toString() {
        return "PersonInfo{" +
                "rawId='" + rawId + '\'' +
                ", display_name='" + display_name + '\'' +
                ", phone='" + phone + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

最後不要忘了新增依賴


 compile 'com.android.support:recyclerview-v7:25.3.1'