Sobes.tech
Middle

Kā pievienot pielāgotus atribūtus pielāgotajai skatai Android?

sobes.tech AI

Atbilde no AI

  1. Atribūtu definēšana attrs.xml: Tiek izveidojiet failu res/values/attrs.xml (vai pievienojiet esošajam). Tajā tiek definēts <declare-styleable> ar jūsu pielāgotā View nosaukumu un uzskaitīti <attr> katram lietotāja atribūtam, norādot to formātu (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. Atribūtu izmantošana XML: XML izkārtojumā, kur tiek izmantots pielāgotais View, tiek pievienoti noteiktie atribūti, izmantojot app nosaukuma telpu.

    <com.example.MyCustomView  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        xmlns:app="http://schemas.android.com/apk/res-auto"  
        app:customText="Hello Custom View"  
        app:customColor="@color/colorPrimary"  
        app:customEnabled="true"/>  
    
  3. Atribūtu lasīšana View kodā: Pēc savas View konstrukcijas (parasti tajā, kas pieņem Context un AttributeSet), tiek izmantotas klases TypedArray un obtainStyledAttributes, lai nolasītu XML norādītās atribūtu vērtības.

    class MyCustomView @JvmOverloads constructor(  
        context: Context,  
        attrs: AttributeSet? = null,  
        defStyleAttr: Int = 0  
    ) : View(context, attrs, defStyleAttr) {  
    
        // Mainīgie atribūtu vērtību glabāšanai
        private var customText: String? = null  
        private var customColor: Int = 0  
        private var customEnabled: Boolean = false  
    
        init {  
            // Iegūt TypedArray ar atribūtiem
            val typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView, defStyleAttr, 0)  
    
            try {  
                // Atribūtu vērtību nolasīšana
                customText = typedArray.getString(R.styleable.MyCustomView_customText)  
                customColor = typedArray.getColor(R.styleable.MyCustomView_customColor, 0) // Noklusējuma vērtība
                customEnabled = typedArray.getBoolean(R.styleable.MyCustomView_customEnabled, false) // Noklusējuma vērtība
    
                // Tagad var izmantot customText, customColor un customEnabled View konfigurēšanai
                // Piemēram:
                // if (customEnabled) { /* ... */ }
    
            } finally {  
                // Svarīgi! `TypedArray` pārstrāde resursu atbrīvošanai
                typedArray.recycle()  
            }  
        }  
    
        // ... pārējā View loģika ...  
    }  
    

obtainStyledAttributes metode atgriež TypedArray, no kura var izvilkt atribūtu vērtības pēc to indeksiem (ko ģenerē R klase). Pēc lietošanas ir jāizsauc recycle() resursu atbrīvošanai.