Значение атрибута формата "android: drawable" недействительно
Я пытаюсь создать пользовательские атрибуты для своей кнопки, но я не знаю, какой формат я должен использовать для изображений в объявлении атрибутов...
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TCButton">
<attr name="Text" format="string"/>
<attr name="BackgroundImage" format="android:drawable" />
</declare-styleable>
</resources>
Ошибка в формате = "android: drawable"...
Ответы
Ответ 1
Вы можете использовать format = "integer" , идентификатор ресурса для рисования и AttributeSet.getDrawable(...).
Вот пример.
Объявить атрибут как целое в res/values /attrs.xml:
<resources>
<declare-styleable name="MyLayout">
<attr name="icon" format="integer" />
</declare-styleable>
</resources>
Задайте атрибут для идентификатора drawable в вашем макете:
<se.jog.MyLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
myapp:icon="@drawable/myImage"
/>
Получите извлечение из атрибута в пользовательском классе компонентов виджета:
ImageView myIcon;
//...
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyLayout);
Drawable drawable = a.getDrawable(R.styleable.MyLayout_icon);
if (drawable != null)
myIcon.setBackgroundDrawable(drawable);
Чтобы увидеть все возможные варианты, проверьте android src здесь
Ответ 2
Я думаю, что лучше использовать его в качестве простой справки:
<declare-styleable name="TCButton">
<attr name="customText" format="string"/>
<attr name="backgroundImage" format="reference" />
</declare-styleable>
И установите его в xml следующим образом:
<your.package.name.TCButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
custom:customText="Some custom text"
custom:backgroundImage="@drawable/myImage"
/>
И в вашем классе задайте такие атрибуты:
public TCButton(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MembershipItemView, 0, 0);
String customText;
Drawable backgroundImage;
try {
customText = a.getString(R.styleable.TCButton_customText);
backgroundImage = a.getDrawable(R.styleable.TCButton_backgroundImage);
} finally {
a.recycle();
}
if(!TextUtils.isEmpty(customText)) {
((TextView)findViewById(R.id.yourTextView)).setText(customText);
}
if(null != backgroundImage) {
((ImageView)findViewById(R.id.yourImageView)).setBackgroundDrawable(backgroundImage);
}
}
PS:
Не забудьте добавить эту строку для корневого элемента макета, который вы используете в пользовательском представлении в
xmlns:custom="http://schemas.android.com/apk/res-auto"
Если вы не установите это, вы не сможете получить доступ к своим пользовательским атрибутам.
Ответ 3
Из кода AOSP я узнал, как инженеры Google объявляют ImageView#src
attr.
<declare-styleable name="ImageView">
<attr name="src" format="reference|color" />
<attr name="scaleType">
<enum name="matrix" value="0" />
<enum name="fitXY" value="1" />
<enum name="fitStart" value="2" />
<enum name="fitCenter" value="3" />
<enum name="fitEnd" value="4" />
<enum name="center" value="5" />
<enum name="centerCrop" value="6" />
<enum name="centerInside" value="7" />
</attr>
<attr name="adjustViewBounds" format="boolean" />
<attr name="maxWidth" format="dimension" />
<attr name="maxHeight" format="dimension" />
<attr name="tint" format="color" />
<attr name="baselineAlignBottom" format="boolean" />
<attr name="cropToPadding" format="boolean" />
<attr name="baseline" format="dimension" />
<attr name="drawableAlpha" format="integer" />
<attr name="tintMode" />
</declare-styleable>
Приведенный выше код является примером, и он может охватывать большинство случаев в нашей разработке.