Valor de atributo de formato "android: drawable" no válido
Estoy tratando de crear atributos personalizados a mi botón, pero no sé qué formato debo utilizar para las imágenes en la declaración de atributos …
<?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>
El error está en el formato = "android: drawable" …
Puede utilizar format = "integer" , el id de recurso de drawable y AttributeSet.getDrawable (…) .
Aquí hay un ejemplo.
Declare el atributo como entero en res / values / attrs.xml:
<resources> <declare-styleable name="MyLayout"> <attr name="icon" format="integer" /> </declare-styleable> </resources>
Establezca el atributo en un ID dibujable en su diseño:
<se.jog.MyLayout android:layout_width="wrap_content" android:layout_height="wrap_content" myapp:icon="@drawable/myImage" />
Obtenga el drawable del atributo en su clase de componente widget personalizado:
ImageView myIcon; //... TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyLayout); Drawable drawable = a.getDrawable(R.styleable.MyLayout_icon); if (drawable != null) myIcon.setBackgroundDrawable(drawable);
Para ver todas las opciones posibles, compruebe el android src aquí
Creo que será mejor usarlo como una simple referencia:
<declare-styleable name="TCButton"> <attr name="customText" format="string"/> <attr name="backgroundImage" format="reference" /> </declare-styleable>
Y establecerlo en su xml como este:
<your.package.name.TCButton android:layout_width="wrap_content" android:layout_height="wrap_content" custom:customText="Some custom text" custom:backgroundImage="@drawable/myImage" />
Y en su clase, establezca los siguientes atributos:
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: No olvide añadir esta línea para el elemento raíz del diseño que está utilizando su vista personalizada en
xmlns:custom="http://schemas.android.com/apk/res-auto"
Si no establece esto, no podrá acceder a sus atributos personalizados.