Sobes.tech
Middle

Como adicionar atributos personalizados para uma view personalizada no Android?

sobes.tech IA

Resposta da IA

  1. Definição de atributos em attrs.xml: Cria-se o ficheiro res/values/attrs.xml (ou adiciona-se a um existente). Nele, define-se <declare-styleable> com o nome da vista personalizada e enumera-se <attr> para cada atributo personalizado, indicando o seu formato (format).

    <?xml version="1.0" encoding="utf-8"?>  
    <resources>  
        <declare-styleable name="MyCustomView">  
            <attr name="customText" format="string"/>  
            <attr name="customColor" format="color"/>  
            <attr name="customEnabled" format="boolean"/>  
        </declare-styleable>  
    </resources>  
    
  2. Utilização de atributos na marcação XML: No layout XML onde a vista personalizada é usada, adicionam-se atributos específicos usando o espaço de nomes app.

    <com.example.MyCustomView  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        xmlns:app="http://schemas.android.com/apk/res-auto"  
        app:customText="Olá Vista Personalizada"  
        app:customColor="@color/colorPrimary"  
        app:customEnabled="true"/>  
    
  3. Leitura de atributos no código da View: No construtor da vista personalizada (normalmente aquele que recebe Context e AttributeSet), usam-se as classes TypedArray e obtainStyledAttributes para ler os valores dos atributos indicados no XML.

    class MyCustomView @JvmOverloads constructor(  
        context: Context,  
        attrs: AttributeSet? = null,  
        defStyleAttr: Int = 0  
    ) : View(context, attrs, defStyleAttr) {  
    
        // Variáveis para guardar os valores dos atributos  
        private var customText: String? = null  
        private var customColor: Int = 0  
        private var customEnabled: Boolean = false  
    
        init {  
            // Obtenção de TypedArray com os atributos  
            val typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView, defStyleAttr, 0)  
    
            try {  
                // Leitura dos valores dos atributos  
                customText = typedArray.getString(R.styleable.MyCustomView_customText)  
                customColor = typedArray.getColor(R.styleable.MyCustomView_customColor, 0) // Valor padrão  
                customEnabled = typedArray.getBoolean(R.styleable.MyCustomView_customEnabled, false) // Valor padrão  
    
                // Agora pode-se usar customText, customColor e customEnabled para configurar a View  
                // Por exemplo:  
                // if (customEnabled) { /* ... */ }  
    
            } finally {  
                // Importante! Liberar recursos chamando recycle()  
                typedArray.recycle()  
            }  
        }  
    
        // ... restante da lógica da View ...  
    }