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

Android wheel 滾輪控件詳解:實作省市區三級聯動

編輯:關於 Android 程式設計

今天來聊聊 wheel 這個控件。它是 GitHub 上的開源專案,用起來相當省事,能做出不少東西——比如自製 datepicker,電商 App 裡常見的省市區三級聯動也是它的典型應用。

先看一下最終要做出的效果:

一、取得 wheel

wheel 可直接從 GitHub 下載。取回後,你可以把其中的 wheel 模組當作 library 引入,也可以只把 Java 類別與 XML 檔複製到自己的專案裡。

二、實作步驟

1. 主版面配置

<relativelayout android:layout_height="match_parent" android:layout_width="match_parent"
  xmlns:android="https://schemas.android.com/apk/res/android">
  <textview android:id="@+id/title" android:gravity="center"
    android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="請選擇城市" />
  <linearlayout android:id="@+id/content" android:layout_below="@id/title"
    android:background="@drawable/layout_bg" android:orientation="horizontal"
    android:layout_height="wrap_content" android:layout_width="fill_parent">
    <kankan.wheel.widget.WheelView android:id="@+id/province_view"
      android:layout_height="wrap_content" android:layout_width="0dp" android:layout_weight="1" />
    <kankan.wheel.widget.WheelView android:id="@+id/city_view"
      android:layout_height="wrap_content" android:layout_width="0dp" android:layout_weight="1" />
    <kankan.wheel.widget.WheelView android:id="@+id/area_view"
      android:layout_height="wrap_content" android:layout_width="0dp" android:layout_weight="1" />
  </linearlayout>
  <button android:id="@+id/confirm" android:layout_below="@id/content"
    android:layout_height="wrap_content" android:layout_width="wrap_content"
    android:onClick="onClick" android:text="確定" />
</relativelayout>

版面中放了三個 WheelView,分別對應省、市、區縣。在 MainActivity 中先取得這三個控件:

provinceView = (WheelView) this.findViewById(R.id.province_view);
cityView = (WheelView) this.findViewById(R.id.city_view);
areaView = (WheelView) this.findViewById(R.id.area_view);

2. 設計資料結構

接著用 ArrayWheelAdapter 做資料適配,它需要兩個參數:上下文與字串陣列。也就是說省、市、區縣都要以陣列形式呈現。但由於一個省對應多個市、一個市對應多個區縣,還需要 Map 來維持關聯關係,因此資料結構設計如下:

private String[] provinceArray;          // 所有省
private Map<String, String[]> citiesMap; // 省 → 市
private Map<String, String[]> areasMap;  // 市 → 區縣

對應的 JSON 格式如下,檔案放在 assets 目錄:

[{ name: "北京", city: [ { name: "北京", area: ["東城區","西城區","崇文區","宣武區"...] } ] } ...]

3. 解析 JSON 並填充資料集

private void initJson() {
  citiesMap = new HashMap<String, String[]>();
  areasMap = new HashMap<String, String[]>();
  InputStream is = null;
  try {
    StringBuffer sb = new StringBuffer();
    is = getAssets().open("city.json");
    int len = -1;
    byte[] buf = new byte[1024];
    while ((len = is.read(buf)) != -1) {
      sb.append(new String(buf, 0, len, "gbk"));
    }
    JSONArray ja = new JSONArray(sb.toString());
    provinceArray = new String[ja.length()];
    String[] citiesArr = null;
    for (int i = 0; i < provinceArray.length; i++) {
      JSONObject jsonProvince = ja.getJSONObject(i);
      provinceArray[i] = jsonProvince.getString("name");
      JSONArray jsonCities = jsonProvince.getJSONArray("city");
      citiesArr = new String[jsonCities.length()];
      for (int j = 0; j < citiesArr.length; j++) {
        JSONObject jsonCity = jsonCities.getJSONObject(j);
        citiesArr[j] = jsonCity.getString("name");
        JSONArray jsonAreas = jsonCity.getJSONArray("area");
        String[] areaArr = new String[jsonAreas.length()];
        for (int k = 0; k < jsonAreas.length(); k++) {
          areaArr[k] = jsonAreas.getString(k);
        }
        areasMap.put(citiesArr[j], areaArr);
      }
      citiesMap.put(provinceArray[i], citiesArr);
    }
  } catch (IOException e) {
    e.printStackTrace();
  } catch (JSONException e) {
    e.printStackTrace();
  } finally {
    if (is != null) {
      try { is.close(); } catch (IOException e) { e.printStackTrace(); }
    }
  }
}

解析本身沒有難點,只是用了三層巢狀迴圈,理清層級關係就不複雜了。

4. 設定 Adapter 與監聽

private void initView() {
  provinceView.setViewAdapter(new ArrayWheelAdapter<String>(MainActivity.this, provinceArray));
  cityView.setViewAdapter(new ArrayWheelAdapter<String>(MainActivity.this, citiesMap.get("北京")));
  areaView.setViewAdapter(new ArrayWheelAdapter<String>(MainActivity.this, areasMap.get("北京")));

  provinceView.setCurrentItem(0);
  cityView.setCurrentItem(0);
  areaView.setCurrentItem(0);

  provinceView.setVisibleItems(7);
  cityView.setVisibleItems(7);
  areaView.setVisibleItems(7);

  provinceView.addChangingListener(this);
  cityView.addChangingListener(this);
}

設定好 Adapter 後再給幾個預設值,並註冊滑動監聽:

@Override public void onChanged(WheelView wheel, int oldValue, int newValue) {
  if (wheel == provinceView) {
    updateCity();   // 省變了,市與區縣都要更新
    updateArea();
  } else if (wheel == cityView) {
    updateArea();   // 市變了,只需更新區縣
  }
}

private void updateCity() {
  int currentIndex = provinceView.getCurrentItem();
  String currentName = provinceArray[currentIndex];
  String[] cities = citiesMap.get(currentName);
  cityView.setViewAdapter(new ArrayWheelAdapter<String>(MainActivity.this, cities));
  cityView.setCurrentItem(0);
}

private void updateArea() {
  int cityIndex = cityView.getCurrentItem();
  int provinceIndex = provinceView.getCurrentItem();
  String proviceName = provinceArray[provinceIndex];
  String currentName = citiesMap.get(proviceName)[cityIndex];
  String[] areas = areasMap.get(currentName);
  areaView.setViewAdapter(new ArrayWheelAdapter<String>(MainActivity.this, areas));
  areaView.setCurrentItem(0);
}

5. 取得選取值

public void onClick(View v) {
  int provinceIndex = provinceView.getCurrentItem();
  String provinceName = provinceArray[provinceIndex];
  int cityIndex = cityView.getCurrentItem();
  String cityName = citiesMap.get(provinceName)[cityIndex];
  int areaIndex = areaView.getCurrentItem();
  Toast.makeText(this, "您選擇的地區是" + provinceName + cityName + areasMap.get(cityName)[areaIndex],
      Toast.LENGTH_SHORT).show();
}

三、微調外觀

功能完成後你會發現預設樣式偏樸素,可以改源碼調整。上下那圈黑邊的顏色定義在 WheelView.java:

private int[] SHADOWS_COLORS = new int[] { 0xFF111111, 0x00AAAAAA, 0x00AAAAAA };

三個值分別是起始色、過渡色與結束色,改成透明即可去掉黑邊。

中間那條半透明分隔條的樣式則定義在 wheel_val.xml:

<shape xmlns:android="https://schemas.android.com/apk/res/android">
  <gradient android:angle="90"
    android:centerColor="#70222222"
    android:endColor="#70EEEEEE"
    android:startColor="#70222222">
    <stroke android:color="#70333333" android:width="1dp" />
  </gradient>
</shape>

依需求替換其中的 color 即可。wheel 的源碼量不大也不難讀,有興趣可以自己翻一翻。

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