Android——读取自己手机的通讯录(RecycleView显示)

参考《第一行代码(第二版)》7.3.2。书中用的是LIstView,因为根本没看ListView,自己用RecyclerView写了一个。
信息类(包括名字和电话):Contents.java

package com.example.contactstest;

public class Contents {
    String name;
    String tel;

    public Contents(String name, String tel) {
        this.name = name;
        this.tel = tel;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }
}

每一条的布局:contents.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <TextView
        android:id="@+id/phone_name"
        android:layout_gravity="left"
        android:layout_margin="2dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
    <TextView
        android:id="@+id/phone_number"
        android:layout_gravity="left"
        android:layout_margin="2dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="?android:attr/listDivider"
        />

</LinearLayout>

适配器ContentsAdapter.java

package com.example.contactstest;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class ContentsAdapter extends RecyclerView.Adapter<ContentsAdapter.ContentsHolder> {
    List<Contents> mContents;

    public ContentsAdapter(List<Contents> contents) {
        mContents = contents;
    }

    @NonNull
    @NotNull
    @Override
    public ContentsHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.contents, parent, false);
        ContentsHolder holder = new ContentsHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull @NotNull ContentsAdapter.ContentsHolder holder, int position) {
        Contents contents = mContents.get(position);
        holder.name.setText(contents.getName());
        holder.number.setText(contents.getTel());
    }

    @Override
    public int getItemCount() {
        return mContents.size();
    }

    class ContentsHolder extends RecyclerView.ViewHolder{
        public TextView number;
        public TextView name;

        public ContentsHolder(@NonNull @NotNull View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.phone_name);
            number = itemView.findViewById(R.id.phone_number);
        }
    }
}

RecyclerView容器activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
</androidx.recyclerview.widget.RecyclerView>

主活动MainActivity.java

package com.example.contactstest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    List<Contents> mContentsList = new ArrayList<>();
    RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = findViewById(R.id.recycler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        /*权限*/
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            /*请求权限*/
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, 1);
        } else {
            readContacts();
        }
    }

    private void readContacts() {
        Cursor cursor = null;
        /*用ContentResolver访问内容提供器中的共享数据*/
        /*ContactsContract.CommonDataKinds.Phone.CONTENT_URI就是通过Uri.parse()方法解析出来的结果*/
        /*cursor保存着联系人信息*/
        cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        if (cursor != null) {
            /*多个cursor,每个里面存了名字和电话*/
            while (cursor.moveToNext()) {
                /*联系人名*/
                String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                /*电话*/
                String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                mContentsList.add(new Contents(displayName, number));
            }
        }
        ContentsAdapter contentsAdapter = new ContentsAdapter(mContentsList);
        recyclerView.setAdapter(contentsAdapter);
        cursor.close();
    }

    /**
     * 请求权限后
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    readContacts();
                }else {
                    Toast.makeText(this, "You denied the permission", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }
}

RecyclerView可以参考我的另一篇: RecyclerView的使用

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CCPigSnail

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值