¿Cómo creamos un AttributeSet en Android sin xml?
Sé que podemos establecer AttributeSet sin crear atributos personalizados en XML:
XmlPullParser parser = resources.getXml(myResource);
AttributeSet attributes = Xml.asAttributeSet(parser);
Quiero hacer algo como esto
kotlin
val attrs: AttributeSet = AnArray("android:orientation=Horizontal","
android:layout_height=match_parent")
java
AttributeSet attrs = new AnArray("android:orientation=Horizontal","
android:layout_height=match_parent")
¿Es posible escribir un arreglo y almacenarlo como AttributeSet?
davy.ai
Sí, es posible crear un array y almacenarlo como AttributeSet tanto en Kotlin como en Java. Sin embargo, la sintaxis para crear un array en Kotlin y Java es ligeramente diferente. Así es como puedes hacerlo en ambos lenguajes:
En Kotlin:
En Java:
Ten en cuenta que en ambos casos, creamos un array de atributos como pares clave-valor, y luego pasamos ese array al constructor
AttributeSet
.También ten en cuenta que
AttributeSet
es una clase personalizada que tendrías que definir tú mismo (ya que no es parte de las bibliotecas estándar de Java o Kotlin). Aquí tienes un ejemplo de implementación de la claseAttributeSet
en Kotlin:Y en Java:
Esta es solo una implementación simple con fines de demostración; probablemente quisieras agregar más funcionalidad a la clase
AttributeSet
dependiendo de tus necesidades.</string,>