CustomViewをXMLレイアウトに宣言する


Chap6. インタフェースベース03-Custom View、Toast、Beap、Vibrationなど
小包名:chap 6 prac 2

完全なコード


  • MainActivity.java
    作成後に変更はありません.

  • MyView.java
  • package ddwucom.mobile.chap6_prac2;
    
    import android.content.Context;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.util.AttributeSet;
    import android.view.View;
    
    import androidx.annotation.Nullable;
    
    public class MyView extends View {
        public MyView(Context context) {
            super(context);
        }
    
        public MyView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); }
    
        public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); }
    
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            canvas.drawColor(Color.YELLOW);
        }
    }
    
  • activity_main.xml
  • <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <ddwucom.mobile.chap6_prac2.MyView
            android:id="@+id/myView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    
        </androidx.constraintlayout.widget.ConstraintLayout>
    //完全なパッケージを含むクラス名で記録する必要があります.
    ddwucom.mobile.chap6_prac2.MyView<-こちら
    //レイアウトの内部にカスタムビューを宣言する必要があります.