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

Android 簡明開發教程十五:RadioButton 與多邊形、路徑繪製

編輯:Android 開發教學

本示例要畫的是多邊形與路徑,並用單選鈕 RadioButton 在 Polys 與 Path 兩個示例之間切換。

UI 的設計是上半部顯示繪圖內容,下半部放兩個單選按鈕。由於版面與 main.xml 不同(main.xml 只有一個 GuidebeeGraphics2DView),因此需要在 res/layout 下另建一個 polys.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:background="@drawable/white"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <com.pstreets.graphics2d.GuidebeeGraphics2DView
    android:id="@+id/graphics2dview"
    android:layout_weight="1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>
  <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:orientation="horizontal" >
    <RadioGroup
      android:layout_width="wrap_content"
      android:orientation="horizontal"
      android:textSize="20dp"
      android:layout_height="wrap_content">
      <RadioButton android:text="Polys"
        android:id="@+id/radioPolys"
        android:layout_width="wrap_content"
        android:textColor="@color/black"
        android:checked="true"
        android:layout_height="wrap_content">
        </RadioButton>
      <RadioButton android:text="Path"
        android:id="@+id/radioPath"
        android:layout_width="wrap_content"
        android:textColor="@color/black"
        android:layout_height="wrap_content">
        </RadioButton>
      </RadioGroup>
  </LinearLayout>
</LinearLayout>

RadioButton 必須包在 RadioGroup 中才構成一個群組,這裡預設將 Polys 設為選中。

版面資源定義好之後,修改 Path.java:

private RadioButton radioPoly;
private RadioButton radioPath;
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.polys);
  graphic2dView = (GuidebeeGraphics2DView) findViewById(R.id.graphics2dview);
  radioPath = (RadioButton) findViewById(R.id.radioPath);
  radioPoly = (RadioButton) findViewById(R.id.radioPolys);
  radioPath.setOnClickListener(this);
  radioPoly.setOnClickListener(this);
}

這段版面有個關鍵細節值得留意:GuidebeeGraphics2DView 上的 android:layout_weight="1"。由於外層是垂直 LinearLayout,加上這個權重後,繪圖區會吃掉所有剩餘空間,把按鈕列擠到最底部。若不設 weight 而給 wrap_content,繪圖區就會依內容收縮,在不同解析度的裝置上呈現高度不一致的結果。這是「自訂 View 加控制列」這種常見版面的標準解法。

另外,這裡用的是 setOnClickListener 而非 RadioGroup.OnCheckedChangeListener。兩者的差別在於:前者每次點擊都會觸發,後者只在勾選狀態真正改變時觸發。當使用者重複點擊已選中的項目時,前者會重繪一次,後者則毫無反應。在切換繪圖模式的情境下兩種都可行,但若你的操作有副作用(例如累加計數、播放音效),就必須選用後者以免重複觸發。

最後記得讓 Activity 實作 OnClickListener 介面,並在 onClick 中依 view 的 id 分派到對應的繪製模式,呼叫 graphic2dView 的重繪方法即可。

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