How to bind method on RadioGroup on checkChanged event with data-binding

前端 未结 5 1699
甜味超标
甜味超标 2021-01-31 09:32

I was searching over the internet for how to perform the new cool android data-binding over the RadioGroup and I didn\'t find a single blog post about it.

5条回答
  •  囚心锁ツ
    2021-01-31 10:04

    Often you care more about what was actually checked instead of "something was checked". In such case alternative solution is to ignore RadioGroup and bind all items as below:

    
            
    
            
    
            
    
    

    where optionA, optionB and optionC are defined in ViewModel like below:

    public final ObservableBoolean optionA = new ObservableBoolean();
    public final ObservableBoolean optionB = new ObservableBoolean();
    public final ObservableBoolean optionC = new ObservableBoolean();
    

    This is usually enough, however if you want to react immediately on click then you can add callBacks and use them like that:

    OnPropertyChangedCallback userChoosedA = new OnPropertyChangedCallback() {
        @Override
        public void onPropertyChanged(Observable sender, int propertyId) {
            (...) // basically propertyId can be ignored in such case
        }
    };
    
    optionA.addOnPropertyChangedCallback(userChoosedA);
    

    Advantage of such approach is that you don't need to compare and track "id".

提交回复
热议问题