როგორ დავამატოთ მომხმარებლის მიერ განსაზღვრული ატრიბუტები 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()-ის გამოძახება რესურსების გასათავისუფლებლად.