Ejemplo de sacar atributo estándar (fondo) en una vista personalizada que tiene su propio estilo predeterminado. En este ejemplo, la vista personalizada PasswordGrid se extiende a GridLayout. Especifiqué un estilo para PasswordGrid que establece una imagen de fondo con el atributo android estándar android: background.
public class PasswordGrid extends GridLayout {
public PasswordGrid(Context context) {
super(context);
init(context, null, 0);
}
public PasswordGrid(Context context, AttributeSet attrs) {
super(context, attrs, R.attr.passwordGridStyle);
init(context, attrs, 0);
}
public PasswordGrid(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
if (!isInEditMode()) {
TypedArray stdAttrs = context.obtainStyledAttributes(attrs,
new int[] { android.R.attr.background }, // attribute[s] to access
defStyle,
R.style.PasswordGridStyle); // Style to access
// or use any style available in the android.R.style file, such as
// android.R.style.Theme_Holo_Light
if (stdAttrs != null) {
Drawable bgDrawable = stdAttrs.getDrawable(0);
if (bgDrawable != null)
this.setBackground(bgDrawable);
stdAttrs.recycle();
}
}
}
Aquí hay parte de mis estilos.archivo xml:
<declare-styleable name="passwordGrid">
<attr name="drawOn" format="color|reference" />
<attr name="drawOff" format="color|reference" />
<attr name="pathWidth" format="integer" />
<attr name="pathAlpha" format="integer" />
<attr name="pathColor" format="color" />
</declare-styleable>
<style name="PasswordGridStyle" parent="@android:style/Widget.GridView" >
<!-- Style custom attributes. -->
<item name="drawOff">@drawable/ic_more</item>
<item name="drawOn">@drawable/ic_menu_cut</item>
<item name="pathWidth">31</item>
<item name="pathAlpha">129</item>
<item name="pathColor">@color/green</item>
<!-- Style standard attributes -->
<item name="android:background">@drawable/pattern_bg</item>
</style>
El mismo problema existe con el tutorial Galería Ver, he visto soluciones que hacen el trabajo tutorial, pero ninguna explicación de por qué el tutorial tendría que ser fijado usando sólo las clases SDK y no añadir su propio xml con el estilo en él. El tutorial se encuentra en http://developer.android.com/resources/tutorials/views/hello-gallery.html el código está en el constructor "ImageAdapter (Context c)" – AGrunewald
Aquí hay una discusión similar http://stackoverflow.com/q/8793183/1307690 – Lemberg