Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 入門教程(三十六):自定義 Adapter 實作手機聯繫人全選

編輯:Android 開發實例

開發 Android 應用時幾乎一定會碰到手機聯繫人,而聯繫人列表通常用 ListView 呈現。若想在每一筆前面放一個 CheckBox,還要能一鍵全選,光靠系統預設的行為是不夠的——關鍵在於自定義 Adapter 與自定義項目版面。

[效果圖]

一、主版面:ListView + 底部全選列

版面分成上下兩塊:上方是占滿剩餘空間的 ListView,下方用 ScrollView 包住一條「全選」列,避免螢幕較小時被擠不見。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <ListView
        android:id="@+id/lvContact"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1.0" />

    <ScrollView
        android:id="@+id/scroll_bottom"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom">

        <LinearLayout
            android:id="@+id/rlall"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <CheckBox
                android:id="@+id/cbSelectAll"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="全選" />
        </LinearLayout>
    </ScrollView>
</LinearLayout>

二、單筆項目版面

每一列由「姓名」與「勾選框」組成。這裡有個容易忽略的細節:CheckBox 必須設成 android:focusable="false",否則它會搶走 ListView 的焦點,導致整列點擊失效。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/contact_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp" />

    <CheckBox
        android:id="@+id/multiple_checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:focusable="false"
        android:clickable="false" />
</LinearLayout>

三、主程式

做法是用 HashMap 記住「第幾列 → 是否勾選」,並繼承 SimpleCursorAdapter 改寫 bindView,在綁定資料的同時同步 CheckBox 的狀態。

package com.demo;

import java.util.HashMap;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class ContactSelectAll extends Activity {

    private CheckBox cbSelectAll;
    private MyAdapter mAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setTitle("聯繫人列表");

        ListView listView = (ListView) findViewById(R.id.lvContact);
        cbSelectAll = (CheckBox) findViewById(R.id.cbSelectAll);

        // 讀取手機聯繫人
        ContentResolver resolver = getContentResolver();
        Uri uri = Uri.parse("content://com.android.contacts/contacts");
        Cursor cursor = resolver.query(uri, null, null, null, null);
        startManagingCursor(cursor);

        // 自定義 Adapter:from 是要寫入的資料列,to 是項目版面中對應的控件 id
        mAdapter = new MyAdapter(getApplicationContext(),
                R.layout.contactlistitem, cursor,
                new String[]{ ContactsContract.Contacts._ID,
                              ContactsContract.Contacts.DISPLAY_NAME,
                              ContactsContract.Contacts.DISPLAY_NAME },
                new int[]{ R.id.contact_name, R.id.contact_name,
                           R.id.multiple_checkbox });
        listView.setAdapter(mAdapter);

        // 全選:一次翻轉所有列的選取狀態
        cbSelectAll.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                for (int i = 0; i < mAdapter.getCount(); i++) {
                    mAdapter.map.put(i, isChecked);
                }
                mAdapter.notifyDataSetChanged();
            }
        });

        // 點整列也能切換勾選
        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> av, View v, int position, long id) {
                CheckBox cb = (CheckBox) v.findViewById(R.id.multiple_checkbox);
                cb.toggle();
                mAdapter.map.put(position, cb.isChecked());
            }
        });
    }

    /** 自定義 Adapter:用 map 保存每一列的勾選狀態 */
    public class MyAdapter extends SimpleCursorAdapter {

        private LayoutInflater mInflater;
        // key = 列的 index,value = 是否勾選
        HashMap<Integer, Boolean> map = new HashMap<Integer, Boolean>();

        public MyAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
            super(context, layout, c, from, to);
            mInflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            // 預設全部未勾選
            for (int i = 0; i < c.getCount(); i++) {
                map.put(i, false);
            }
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            LinearLayout ll;
            if (view == null) {
                ll = (LinearLayout) mInflater.inflate(R.layout.contactlistitem, null);
            } else {
                ll = (LinearLayout) view;
            }

            int nameCol = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            final int position = cursor.getPosition();

            TextView txtName = (TextView) ll.findViewById(R.id.contact_name);
            txtName.setText(cursor.getString(nameCol));

            final CheckBox ckSel = (CheckBox) ll.findViewById(R.id.multiple_checkbox);
            // 單敲 CheckBox 時同步 map
            ckSel.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    map.put(position, isChecked);
                }
            });
            // 依 map 還原勾選狀態(捲動回收後才不會跑掉)
            ckSel.setChecked(map.get(position));
        }
    }
}

這裡有兩個實務上該注意的地方。第一,bindView 每次都會重畫可見列,所以務必在最後呼叫 setChecked(map.get(position)) 還原狀態,否則捲動時勾選會錯位。第二,範例使用的是舊版 ContactsContract 介面;在 Android 6.0 以後,讀取聯繫人屬於敏感權限,除了宣告權限之外還必須在執行期向使用者動態詢問,否則會直接拿到空資料。

四、别忘了權限

最後在 AndroidManifest.xml 補上讀取聯繫人的權限,執行即可看到效果。

<uses-permission android:name="android.permission.READ_CONTACTS" />
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved