hyoromoのブログ

最近はVRSNS向けに作ったものについて書いています

独自クラスをLayoutに定義してみたよ

何かのwidgetを継承して作ったクラスならlayoutに定義できるようです。

やりかた

まずは何かのwidgetを継承したクラスを用意します。今回はメンドウなのでviewを2つ用意しました。

public class HogeView1 extends View {
    public HogeView1(Context context, AttributeSet attrs) {
        super(context, attrs);
        setFocusable(true);
    }

    /**
     * 描画処理
     */
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        /* 背景色を設定 */
        canvas.drawColor(Color.RED);

        /* 描画するための線の色を設定 */
        Paint mainPaint = new Paint();
        mainPaint.setStyle(Paint.Style.FILL);
        mainPaint.setColor(Color.BLUE);

        /* 円で描画 */
        canvas.drawCircle(30, 100, 10, mainPaint);
    }
}
public class HogeView2 extends View {
    public HogeView2(Context context, AttributeSet attrs) {
        super(context, attrs);
        setFocusable(true);
    }

    /**
     * 描画処理
     */
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        /* 背景色を設定 */
        canvas.drawColor(Color.BLUE);

        /* 描画するための線の色を設定 */
        Paint mainPaint = new Paint();
        mainPaint.setStyle(Paint.Style.FILL);
        mainPaint.setColor(Color.RED);

        /* 円で描画 */
        canvas.drawCircle(30, 100, 10, mainPaint);
    }
}

ここでの注意点はコンストラクタ
public ××××(Context context, AttributeSet attrs)
と、引数にAttributeSetがあるモノを使用してください。layoutから読むのに必須です。

XML定義

継承したviewを2つ、普通のbuttonを1つ定義します。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="2"
    >
        <hyoromo.android.democustomlayout.HogeView1
            android:id="@+id/view1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
        ></hyoromo.android.democustomlayout.HogeView1>
        <hyoromo.android.democustomlayout.HogeView2
            android:id="@+id/view2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
        ></hyoromo.android.democustomlayout.HogeView2>
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_weight="1"
    >
        <Button
            android:id="@+id/btn"
            android:text="change"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
        ></Button>
    </LinearLayout>
</LinearLayout>

タグをパッケージ名にすればOKです。注意点はそのくらい。
これを実行したら以下のようになります。
device