レイアウトのxmlで設定された android:checked="true" などの属性を取得する

SDKのサンプルを見ても、いまいちスタイルの使い方が理解できていなかったんだけど、Tuboroidのソースを読んでやっとわかった。


Viewのコンストラクタに渡ってくる AttributeSet と R.styleable や R.attr の関係がわかってしまえば簡単。
たとえば layout の xml で設定された android:checkedandroid:focusable を取得したいときはこんな風に書ける。

TypedArray a = context.obtainStyledAttributes(
        attrs, 
        new int [] { android.R.attr.focusable, android.R.attr.checked });

boolean focusable = a.getBoolean(0, true);
boolean checked = a.getBoolean(1, false);

obtainStyledAttributes() に渡す int の配列は、R.attr.* の値を配列にして渡す。
返ってきた TypedArray は渡した配列の順番で結果が戻ってくるということ。
これを理解してれば自分で書いた attrs.xml と自動生成される R.styleable の関係がわかる。


ただ、ひとつ注意が必要なのは、obtainStyledAttributes に渡す int の配列は、ソートされた状態である必要があるということ。上の例では配列を focusable, checked の順にしているけど、これを逆にすると最初の checked の値しか取得できない。