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

把自定義 View 放進 FrameLayout:實現多控制項疊加顯示

編輯:關於 Android 程式設計

如果想在自定義的 View 之上再顯示 Button 等其他控制項,該怎麼做呢?可以透過 FrameLayout 來實現多組件的疊加顯示,整個過程可以拆成兩個步驟。

步驟一:撰寫自定義 View

在自定義 View 類別中覆寫父類的構造方法(注意要使用「兩個參數」的那個版本),並在 onDraw 中繪製你想要的內容:

public class MyView2 extends View {
    public MyView2(Context context, AttributeSet att) {
        super(context, att);
    }
    public void onDraw(Canvas c) {
        // 在這裡繪製你要的內容
    }
}

步驟二:定義佈局檔

接著在佈局檔中,用 FrameLayout 把自定義 View 與其他控制項疊放安排:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <com.lovose.MyView2
        android:id="@+id/View01"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    </com.lovose.MyView2>
    <AbsoluteLayout android:id="@+id/AbsoluteLayout01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <Button android:text="Button01"
            android:id="@+id/Button01"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_x="100dip"
            android:layout_y="100dip"></Button>
    </AbsoluteLayout>
</FrameLayout>

透過這種方式,自定義 View 與 Button 等控制項就能在 FrameLayout 中彼此疊放,你可以自由地安排 UI 的呈現方式了。

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