属性をスタイル可能と宣言するかどうかの違いは次のとおりだと思います。
attrs.xml では、"resources" セクション内で直接、または "declare-styleable" 内で、カスタム属性を宣言できます。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="attrib1" format="string" />
<declare-styleable name="blahblah">
<attr name="attrib2" format="string" />
</declare-styleable>
そのため、「attrib1」をスタイル不可として定義し、「attrib2」をスタイル可能として定義しました。
ではlayout/someactivity.xml
、これらの属性を直接使用できます (名前空間は必要ありません)。
<com.custom.ViewClass attrib1="xyz" attrib2="abc"/>
宣言内で「styleable」属性「attrib2」を使用できますstyle.xml
。ここでも、名前空間は必要ありません (レイアウト XML で名前空間が使用されていたとしても)。
<style name="customstyle" parent="@android:style/Widget.TextView">
<item name="attrib2">text value</item>
<!-- customize other, standard attributes too: -->
<item name="android:textColor">@color/white</item>
</style>
次に、スタイルごとに属性を設定することもできます。
<com.custom.CustomView attrib1="xyz" style="@style/customstyle"/>
これを行うと仮定しましょう: attrib1
XML で直接設定attrib2
し、スタイルで設定します。
他の場所で、「blahblah
」はこれらの属性を使用するカスタム ビュー クラスの名前でなければならず、レイアウト XML でカスタム属性を参照するには名前空間を使用する必要があるという説明を見ました。しかし、これはどれも必要ないようです。
スタイル化可能と非スタイル化の違いは次のようです。
style.xml
" " 宣言でスタイル可能な属性を使用できます。
obtainStyledAttributes()
カスタム クラスのコンストラクターは、スタイル付き属性とスタイルなし属性を別の方法で読み取る必要がありますattr.getAttributeValue()
。
私が Web で見たほとんどのチュートリアルと例では、 のみobtainStyledAttributes()
が使用されていました。ただし、これは、スタイルを使用せずにレイアウトで直接宣言された属性では機能しません。obtainStyledAttributes()
ほとんどのチュートリアルで示されているように行うと、属性attrib1
はまったく取得されません。attrib2
スタイルで宣言されているため、取得するだけです。作品を使用した直接的な方法attr.getAttributeValue()
:
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
String attrib1 = attrs.getAttributeValue(null, "attrib1");
// do something with this value
}
" " を宣言するために名前空間を使用しなかったため、 に名前空間引数としてattrib1
渡します。null
getAttributeValue()