カスタムビューに独自のスタイル属性を定義する
メディアのサムネイルを同じ大きさで横一列に並べるコンテナクラスを作ったので、中にいれるサムネイルの数をレイアウトリソースで定義できるようにした。
res/values/attr.xml
にdeclare-styleable
を追加する
<resources> <declare-styleable name="MyCustomView"> <attr name="thumbCount" format="integer" /> </declare-styleable> </resources>
layoutリソースファイルで次のように使う
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" > <com.freshdigitable.MyCustomView android:id="@+id/custom_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" app:thumbCount="4" /> </LinearLayout>
独自のネームスペースを定義しようとしたら、「gradleプロジェクトではapp:.../res-auto
を使え」的なことを言われた気がする。
カスタムビューのコンストラクタで設定した値を受け取る
(色々と省略している)
public class MyCustomView extends View { private final int thumbCount; public MyCustomView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView, defStyle, 0); try { this.thumbCount = a.getInt(R.styleable.MyCustomView_thumbCount, 0); } finally { a.recycle(); } } }