Ինչպես ավելացնել օգտագործողի հատկություններ՝ հատուկ դիտում 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() ռեսուրսների ազատման համար։