0
1

More than 1 year has passed since last update.

Custom View にデフォルトの属性群を指定する方法

Last updated at Posted at 2021-10-17

◆はじめに

特定の custom view すべてに適用されるデフォルトの属性値を指定する方法のメモです。

◆具体的なケース

例えば MyTextView という custom view を作った際に、以下のようにデフォルトのスタイルを毎回差し込む必要があるとします。

<MyTextView
    android:id="@+id/artist_name_text_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    style="@style/myTextView"
/>

この場合、custom view の恩恵が薄くなってしまうし、style の設定し忘れをコンパイル時に検出できなかったりして、とっても残念な感じです。

ということで、デフォルト属性を指定したいよねという話です。

※ちなみに、カスタムの属性を指定する方法は簡単で、attrs.xml に属性を定義して、custom view 側のコンストラクタで渡ってくる attrs から値を取得すればOKです。興味のある方は 過去記事 参照のこと。

◆実装例

☆Custom View

デフォルトの属性を指定したい custom view です。

引数を2つ持つコンストラクタにて、親クラスのコンストラクタの第3引数に、デフォルト属性用の attr を渡します。
R.attr.myTextViewStyle は後述。

MyTextView.kt
class MyTextView : AppCompatTextView {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs, R.attr.myTextViewStyle)
    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
}

☆attrs.xml

Custom view から参照される attr です。
※この attr とデフォルト属性群の関連付けは後述。

attrs.xml
<resources>
    <attr name="myTextViewStyle" type="reference" />
</resources>

☆styles.xml

myTextViewStyle とデフォルト属性群を関連付けます。

styles.xml
<resources>
    <!-- アプリの Theme 設定 -->
    <style name="AppTheme" parent="Theme.MaterialComponents.Light">
        <!-- myTextViewStyle とデフォルト属性群の関連付け  -->
        <item name="myTextViewStyle">@style/MyTextView</item>
    </style>

    <!-- MyTextView 全てに適用されるデフォルト属性 -->
    <style name="MyTextView">
        <item name="android:ellipsize">end</item>
        <item name="android:maxLines">1</item>
        <item name="android:textSize">12dp</item>
    </style>
</resources>

◆おわりに

らくちんですね~

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1