Sobes.tech
Middle

Android'de özel görünüm için özel öznitelikler nasıl eklenir?

sobes.tech yapay zeka

AI'dan gelen yanıt

  1. attrs.xml içinde özniteliklerin tanımı: res/values/attrs.xml dosyası oluşturulur (veya mevcut bir dosyaya eklenir). Bu dosyada <declare-styleable> özelleştirilmiş View'un adıyla tanımlanır ve her özel öznitelik için <attr> listelenir, formatı (format) belirtilir.

    <?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. XML düzenlemesinde özniteliklerin kullanımı: Özelleştirilmiş View'un kullanıldığı XML düzenlemesinde, app isim alanı kullanılarak belirli öznitelikler eklenir.

    <com.example.MyCustomView  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        xmlns:app="http://schemas.android.com/apk/res-auto"  
        app:customText="Merhaba Özelleştirilmiş View"  
        app:customColor="@color/colorPrimary"  
        app:customEnabled="true"/>  
    
  3. View kodunda özniteliklerin okunması: Özelleştirilmiş View'un yapıcı metodunda (genellikle Context ve AttributeSet alan), TypedArray ve obtainStyledAttributes sınıfları kullanılarak XML'de belirtilen özniteliklerin değerleri okunur.

    class MyCustomView @JvmOverloads constructor(  
        context: Context,  
        attrs: AttributeSet? = null,  
        defStyleAttr: Int = 0  
    ) : View(context, attrs, defStyleAttr) {  
    
        // Öznitelik değerlerini saklamak için değişkenler  
        private var customText: String? = null  
        private var customColor: Int = 0  
        private var customEnabled: Boolean = false  
    
        init {  
            // Özniteliklerle TypedArray alınması  
            val typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView, defStyleAttr, 0)  
    
            try {  
                // Özniteliklerin değerlerinin okunması  
                customText = typedArray.getString(R.styleable.MyCustomView_customText)  
                customColor = typedArray.getColor(R.styleable.MyCustomView_customColor, 0) // Varsayılan değer  
                customEnabled = typedArray.getBoolean(R.styleable.MyCustomView_customEnabled, false) // Varsayılan değer  
    
                // Artık customText, customColor ve customEnabled kullanılabilir  
                // Örneğin:  
                // if (customEnabled) { /* ... */ }  
    
            } finally {  
                // Kaynakları serbest bırakmak için recycle() çağrısı önemli  
                typedArray.recycle()  
            }  
        }  
    
        // ... diğer View mantığı ...  
    }