Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android ListView 選擇模式的實現詳解

編輯:關於 Android 程式設計

我們大概都曾接過這樣的需求:一堆數據擺在用戶面前,以列表形式呈現,讓他們從中單選或多選,最後拿到選中的結果去做下一步操作。面對這種需求,聰明的程序員們總能想到各種解法。就拿我說吧——雖然算不上聰明,但也勉強想到了。

【也許這樣實現就對了】

對於需要選擇的列表數據,我習慣在 adapter 綁定的數據實體裡加一個標記,用來表示是否被選中;點擊時遍歷並修改 adapter 中的實體標記,再通知刷新,然後在 getView 裡根據標記改變視圖樣式。這樣做很直觀,能實現我們要的效果。

【探索更好的方案】

上面那種做法大家估計都能想到,但它存在兩個問題:一是遍歷的效率偏低,二是 adapter 裡會摻進一些「非功能性」的代碼,讓它變得臃腫複雜。當我們真正吃透 ListView 之後,就會發現它自帶一個屬性——choiceMode,翻譯過來就是「選擇模式」。

【選擇模式實例】

下面我用一個簡單的例子演示如何在單選模式下使用選擇模式。關鍵在於自定義 View——這或許是這種方式唯一的短板:必須自己寫一個自定義的列表項。

【自定義選項】

自定義的列表項繼承 Checkable,在其方法中修改列表項的界面狀態。

package com.change.selectablelistviewdemo;

import android.content.Context;
import android.widget.CheckBox;
import android.widget.Checkable;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.change.selectablelistviewdemo.R;

/**
 * 自定義選項 view,實現 Checkable。在實現的方法中修改界面狀態。
 * @author Change
 */
public class SelectItemView extends LinearLayout implements Checkable {
    CheckBox cbx;
    TextView name;

    public SelectItemView(Context context){
        super(context);
        inflate(getContext(), R.layout.item_select, this);
        cbx = (CheckBox)findViewById(R.id.cbx);
        name = (TextView)findViewById(R.id.name);
    }

    @Override
    public boolean isChecked() {
        return cbx.isChecked();
    }

    @Override
    public void setChecked(boolean arg0) {
        cbx.setChecked(arg0);
    }

    @Override
    public void toggle() {
        cbx.toggle();
    }

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

我的列表項只有一個顯示名字的 TextView 和一個代表單選狀態的選擇框。這裡有個關鍵細節:需要取消 CheckBox 自身的點擊與焦點獲取,把它的狀態完全交由列表項的點擊來決定。布局代碼如下:

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

    <TextView
        android:id="@+id/name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".9" />

    <CheckBox
        android:id="@+id/cbx"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_weight=".1"
        android:clickable="false"
        android:focusable="false"
        android:focusableInTouchMode="false"
        />
</LinearLayout>

【如何使用 ListView】

非常簡單,在主界面的 XML 裡定義 ListView,並設置 choiceMode,此處用 singleChoice 表示單選模式。

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://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"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="choice"
        android:text="current"
        android:layout_below="@+id/lv"
        />

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/lv"
        android:choiceMode="singleChoice"
        />
</RelativeLayout>

【主 Activity 做了什麼】

Activity 只負責把 ListView 的數據綁定到界面,這裡用的是一個內部類形式的 adapter。它簡單得出奇——只設置了名字的顯示,剩下的選擇狀態完全交給 ListView 的機制和自定義 View 去處理。是不是很省心?

package com.change.selectablelistviewdemo;

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

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.Toast;

/**
 * ListView 單選模式 demo
 * @author Change
 */
public class MainActivity extends Activity {
    List<String> names = new ArrayList<String>();
    ListView lv;
    SelAdapter adapter = new SelAdapter();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv = (ListView)findViewById(R.id.lv);
        initData();
        lv.setAdapter(adapter);
    }

    private void initData(){
        for(int i=0;i<10;i++){
            names.add("name"+i);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    /**
     * 列表適配器,只需要設置 view 的內容,狀態變化完全交由 android 機制和自定義 view。
     * @author Change
     */
    class SelAdapter extends BaseAdapter{
        @Override
        public int getCount() {
            return names.size();
        }

        @Override
        public Object getItem(int arg0) {
            return names.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            return arg0;
        }

        @Override
        public View getView(int arg0, View arg1, ViewGroup arg2) {
            if(null==arg1){
                arg1 = new SelectItemView(MainActivity.this);
            }
            ((SelectItemView)arg1).setName(names.get(arg0));
            return arg1;
        }
    }

    public void choice(View v){
        int pos = lv.getCheckedItemPosition();
        if(ListView.INVALID_POSITION!=pos){
            Toast.makeText(MainActivity.this, "current pos="+pos, Toast.LENGTH_SHORT).show();
        }
    }
}

就是這麼簡單——把選擇狀態託付給系統機制與自定義 View,我們的 adapter 瞬間清爽了不少。趕緊動手試試吧。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved