Androidのカスタムビューについて

Androidでカスタムビューを作る.

ここを見ながら作る.

developer.android.com

  • カスタムビューを作る際,方針が3つある.
    • Viewを拡張してゼロから作る
    • ViewGroup系のクラス(例:ConstraintLayout)を拡張して,既存のViewの組み合わせたカスタムビューを作る
    • 既存の具体的なView(例:TextView)を拡張して,既存のViewを拡張したカスタムビューを作る

Viewを拡張してゼロから作る場合

雰囲気コード

CustomView.kt

class CustomView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
    View(context, attrs, defStyleAttr) {

    val contentText: String
    private val paint: Paint

    init {
        val a = context.theme.obtainStyledAttributes(
            attrs,
            R.styleable.CustomView,
            defStyleAttr, 0)

        contentText = a.getString(R.styleable.CustomView_contentText)!!

        paint = Paint(Paint.ANTI_ALIAS_FLAG)
        paint.textSize = 60.0f
        paint.style = Paint.Style.FILL
        a.recycle()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        canvas.drawCircle(x, y, 60.0f, paint)
        canvas.drawText(contentText, x, y, paint)
    }
}

values/attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomView">
        <attr name="contentText" format="string" />
    </declare-styleable>
</resources>

view_use_customview.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="wrap_content"
    tools:orientation="horizontal">

    <CustomView
        android:id="@+id/customView"
        android:layout_width="303dp"
        android:layout_height="224dp"
        android:layout_marginTop="200dp"既存のViewの組み合わせたカスタムビューを作る
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintHorizontal_bias="0.629"
        app:layout_constraintVertical_bias="1.0"
        app:contentText="あーあーあいうえお" />

</androidx.constraintlayout.widget.ConstraintLayout>

f:id:akrfjmt:20190624144158p:plain

既存のViewの組み合わせたカスタムビューを作る場合

(後で書く)