2017.12.4 Android开发之ListView组件

 

1.修改布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.chuny.ch10listview.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/listview"></ListView>
</LinearLayout>

 

2.修改Java文件:

 

3.运行效果:

 

 

4.介绍三种适配器:

(1)读取手机通讯录的信息的方法:读取数据

    private List<String> getContactName(){
        List<String> contacts=new ArrayList<>();                  //List<String>指定List的类型只能是String
          //定义一个内容解析器,就是凡是读到手机系统资源的,都需要一个内容解析器
        ContentResolver cr=getContentResolver();
        //获取手机通信录的地址
        Cursor cursor=cr.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);        //定义一个游标,URI是手机通讯录,也可以改为手机短信的URI

        //循环读取通讯录里边的联系人
        if(cursor.moveToFirst()){
            do{
                String name=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));        //游标类型转化为数据类型
                //读取手机通信录中的联系人姓名
                contacts.add(name);
            }while(cursor.moveToNext());
        }
        cursor.close();     //关闭游标,游标类似指针,读取数据库时
        return contacts;
    }

定义适配器:

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView=(ListView)findViewById(R.id.listview);
       // ArrayAdapter<String> adapter=new ArrayAdapter<String>(MainActivity.this,R.layout.support_simple_spinner_dropdown_item,dataSource);
        //listView.setAdapter(adapter);
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(MainActivity.this,R.layout.support_simple_spinner_dropdown_item,getContactName());
        listView.setAdapter(adapter);
    }

报错:

修改权限:安卓中调用不同资源,需要不同的权限

 

 运行效果:

 这个程序运行在Android6.0以及以上版本,会发生还是未授权的现象:因为Android6.0以及以上的都需要二次授权(按照组来划分的,给了一个权限就等于这个组内的权限都给了)

API大于等于23以后的授权方式的更改:

1.在Mainfest文件中定义,安装的时候用户必须同意才能安装

2.在用户执行程序的时候问用户要权限

 

(2)SimpleCursorAdapter

(3)SimpleAdapter:可以自定义显示的样式,最好用的一个Adapter

首先自己定义一个布局文件,用户显示每一个数据的内容格式,用于循环显示数据:

 

posted @ 2017-12-11 15:07  小春熙子  阅读(193)  评论(0编辑  收藏  举报