android databing 의 세 가지 사용자 정의 속성 방식
반년 동안 의 사용 을 통 해 databing 은 세 가지 사용자 정의 속성 방식 이 있 음 을 발견 하 였 다.각각:
2.1 xml 는 사용자 정의 속성 라벨 을 도입 합 니 다.코드 는 @ BindingAdapter 주 해 를 통 해 바 인 딩 이 완료 되 었 습 니 다.
xml 파일:
<declare-styleable name="AdapterView">
  
  <attr name="setCheckValue" format="boolean"/>
declare-styleable>
코드 파일:
public class ViewAdapter {
    @BindingAdapter({"setCheckValue"})
    public static void setCheckValue(final CheckBox checkBox, final ObservableField<Boolean> tags){
        tags.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                checkBox.setChecked(tags.get());
            }
        });
    }
}
메모: xml 에서 attr name 을 정의 할 때 format 라벨 을 추가 하지 않 으 면 xml 레이아웃 에서 사용 할 때 사용자 정의 이 속성 으로 이동 할 수 없습니다.넣 어야 점프 할 수 있어 요.
여기 코드 에 사용 되 는 자바 코드, 자바 코드 대응 은 static 정적 함수 입 니 다.kotlin 코드 에 대응 하려 면 정적 인 방식 으로 몇 가지 방법 이 있 습 니 다.
2.1.1. 예 를 들 어 가장 바깥쪽 은 kotlin 의 단일 예 로 쓰 고 방법 전에 @ JvmStatic 주 해 를 추가 합 니 다.
예 를 들 면:
object LinearLayoutViewAdapter {
 
    @JvmStatic
    @Suppress("UNCHECKED_CAST")
    @BindingAdapter(value = ["itemBinding", "items"], requireAll = false)
    fun <T> setAdapter(linearLayout: LinearLayout,
                       itemBinding: ItemBinding<T>?,
                       items: List<T>?) {
        requireNotNull(itemBinding) { "itemBinding == null" }
        val oldAdapter: BindingLinearLayoutAdapter<T>? = linearLayout.getAdapter() as? BindingLinearLayoutAdapter<T>
        val adapter = oldAdapter ?: BindingLinearLayoutAdapter()
        adapter.itemBinding = itemBinding
        adapter.setItems(items)
        if (adapter != oldAdapter) {
            linearLayout.setAdapter(adapter)
        }
    }
}
2.1.2, kotin 의 확장 함수 로 작성:
다음 코드
@BindingAdapter(value = ["labelCheckChecked"], requireAll = false)
fun LabelCheckBoxView.setEnable(labelCheckChecked: Boolean) {
    this.getCheckBox().isChecked = labelCheckChecked
}
2.1.3 kotlin 은 정적 인 방법 도 있 는데 함수 식 프로 그래 밍 방식 으로 클래스 를 설정 하지 않 고 함 수 를 직접 쓰 는 것 이다.
예 를 들 어 구 글 홈 페이지 의 demo 쓰기
@BindingAdapter("android:paddingLeft")
    fun setPaddingLeft(view: View, padding: Int) {
        view.setPadding(padding,
                    view.getPaddingTop(),
                    view.getPaddingRight(),
                    view.getPaddingBottom())
    }
2.2, @ BindingMethods + @ BindingAdapter 의 방식
xml 에 속성 을 쓸 필요 가 없고 코드 를 직접 사용 합 니 다.사용 할 때 도 팁 을 드 립 니 다.
@RestrictTo(RestrictTo.Scope.LIBRARY)
@BindingMethods(BindingMethod(type = LabelCheckBoxView::class, attribute = "onCheckedChangedCommand", method = "setCheckedChanged"),
        BindingMethod(type = LabelCheckBoxView::class, attribute = "labelCheckChecked", method = "setEnable"))
class ViewAdapter
 
 
/**
 *       
 * Desc:
 * 
 * Author: LiWei
 * Date: 2019-12-27
 * @receiver LabelCheckBoxView
 * @param bindingCommand BindingCommand
 */ 
@BindingAdapter(value = ["onCheckedChangedCommand"], requireAll = false)
fun LabelCheckBoxView.setCheckedChanged(bindingCommand: BindingCommand<Boolean>) {
    this.getCheckBox().setOnCheckedChangeListener { compoundButton, b -> bindingCommand.execute(b) }
}
 
@BindingAdapter(value = ["labelCheckChecked"], requireAll = false)
fun LabelCheckBoxView.setEnable(labelCheckChecked: Boolean) {
    this.getCheckBox().isChecked = labelCheckChecked
}
2.3. 컨트롤 속성 을 사용자 정의 할 때 set 를 제공 하 는 방법 은 databinding 사용자 정의 속성 을 직접 지원 합 니 다.
<declare-styleable name="LabelCheckBoxView">
    <attr name="labCheckTip" format="string" />
    <attr name="labCheckSelect" format="boolean" />
declare-styleable>
 
class LabelCheckBoxView @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
 
    /**
     *   Tv
     */
    private var tipStr: String? = ""
 
 
    init {
        orientation = HORIZONTAL
        View.inflate(context, R.layout.widget_label_checkbox, this)
        if (attrs != null) {
            val a = getContext().obtainStyledAttributes(attrs, R.styleable.LabelCheckBoxView)
            if (a.hasValue(R.styleable.LabelCheckBoxView_labCheckTip)) {
                tipStr = a.getString(R.styleable.LabelCheckBoxView_labCheckTip)
            }
 
            //      ,       
            if (a.hasValue(R.styleable.LabelCheckBoxView_labCheckSelect)) {
                switchLabel.isSelected = a.getBoolean(R.styleable.LabelCheckBoxView_labCheckSelect, false)
            }
 
            a.recycle()
        }
        tvLabelTip.text = tipStr
    }
 
...
...
 
    /**
     *       ,         dataBinding
     * Desc:
     * 
     * Author: xx
     * Date: 2019-12-27
     * @param str String
     */
    fun setLabCheckTip(str: String) {
        tvLabelTip.text = str
    }
 
    /**
     *       ,         dataBinding
     * Desc:
     * 
     * Author: xx
     * Date: 2019-12-27
     * @param select Boolean
     */
    fun setLabCheckSelect(select: Boolean) {
        switchLabel.isSelected = select
    }
}
3 、 참조 【 1 】 、 홈 페이지https://developer.android.com/topic/libraries/data-binding/binding-adapters#kotlin
【 2 】, androidx. databing. adapters 원본 코드
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Kotlin의 기초 - 2부지난 글에서는 Kotlin이 무엇인지, Kotlin의 특징, Kotlin에서 변수 및 데이터 유형을 선언하는 방법과 같은 Kotlin의 기본 개념에 대해 배웠습니다. 유형 변환은 데이터 변수의 한 유형을 다른 데이터...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.