Androidда өзгөчөлөнгөн көрүнүш үчүн колдонуучу белгилерин кантип кошуу керек?
sobes.tech AI
AIден жооп
-
attrs.xml'де атрибуттарды аныктоо:
res/values/attrs.xmlфайлын түзөбүз (же бар файлга кошобуз). Анын ичинде<declare-styleable>менен өзүнүн View атын көрсөтөбүз жана<attr>аркылуу ар бир колдонуучу атрибут үчүн анын форматын (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> -
XMLде атрибуттарды колдонуу: XML макетинде, өзгөчө View колдонулганда,
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="Hello Custom View" app:customColor="@color/colorPrimary" app:customEnabled="true"/> -
View кодуна атрибуттарды окутуу: Өзгөчө View конструкторунда (көбүнчө
ContextжанаAttributeSetкабыл алган жерде),TypedArrayжанаobtainStyledAttributesкласстары аркылуу XMLде көрсөтүлгөн атрибуттардын маанилерин окуйбуз.class MyCustomView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { // Атрибуттардын маанилерин сактоо үчүн өзгөрмөлөр private var customText: String? = null private var customColor: Int = 0 private var customEnabled: Boolean = false init { // TypedArray алуу val typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView, defStyleAttr, 0) try { // Атрибуттардын маанилерин окутуу customText = typedArray.getString(R.styleable.MyCustomView_customText) customColor = typedArray.getColor(R.styleable.MyCustomView_customColor, 0) // Дефолт мааниси customEnabled = typedArray.getBoolean(R.styleable.MyCustomView_customEnabled, false) // Дефолт мааниси // Эми customText, customColor жана customEnabled колдонуп View'ди конфигурациялай аласыз // Мисалы: // if (customEnabled) { /* ... */ } } finally { // маанилүү! `TypedArray` кайра колдонуу үчүн ресурстарды бошотуу typedArray.recycle() } } // ... калган View логикасы ... }
obtainStyledAttributes методу TypedArray кайтарат, андан атрибуттардын маанилерин алардын индексине карап чыгууга болот (бул R классы тарабынан түзүлөт). Колдонгондон кийин recycle() чакырышы зарыл, ресурстарды бошотуу үчүн.