RecyclerViewで使いまわしたいと思って調べた。二つ方法がある。
自分はCanvasが使えないので二つ目の方が楽だった。
1、形はコードで書く
下の奴が形を描画する。
class RectFormView : View {
private var paint:Paint = Paint()
//角丸つきの四角(矩形)
private var rectf: RectF = RectF(0f,50f,50f,0f)
constructor(context: Context) : super(context)
//下の二つのconstructorがないとxmlでエラーがでる
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
//エラー内容
//Custom view CustomView is not using the 2- or 3-argument View constructors; XML attributes will not work
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
override fun onDraw(canvas: Canvas){
paint.color = Color.argb(255, 255, 0, 255)
//Paint.Style.STROKEで使えるが今回はFILLなので意味ない
//paint.strokeWidth = 20f
//塗りつぶし
paint.style = Paint.Style.FILL
//drawRectとdrawCircleとかもあった
canvas.drawRoundRect(rectf,10f,10f,paint)
}
}
あとはこれをXMLで呼び出すだけ。
<work.prgrm.RectFormView android:id="@+id/item_rect" android:layout_width="wrap_content" android:layout_height="wrap_content" />
これだとアプリを起動するまでどういう風に描画されるかわからなかったので少し不便だった。
2、全部XMLで書く
角丸などの設定をするファイルをdrawableの下に作る。
今回はshape_rectという名前。
shape_rect.xml
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape android:shape="rectangle"> <corners android:topRightRadius="10dp" android:bottomRightRadius="10dp" android:bottomLeftRadius="10dp" android:topLeftRadius="10dp" /> <solid android:color="@color/button_material_light" /> </shape> </item> </selector>
あとは任意のviewでbackgroundで指定してこれを呼び出す。
<View android:id="@+id/item_view_rect" android:layout_width="50dp" android:layout_height="50dp" android:background="@drawable/shape_rect" />
Custom view CustomView is not using the 2- or 3-argument View constructors; XML attributes will not work
が少しうざかったし解決してもちゃんと描画されているか見られなかった。