Can I databind a ProgressBar in Android?

前端 未结 4 1779
一向
一向 2021-02-13 15:37

Is it possible to use data-binding for a SeekBar or ProgressBar in Android? I have this data element:


  

        
4条回答
  •  不思量自难忘°
    2021-02-13 15:59

    In case it helps someone, this question comes up under search a lot, this can now be done using two-way databinding. I use two bindable values below, I tend to prefer no display logic in the XML itself, but I suspect it can work with just one as well.

    Create the bindable values in your ViewModel, one for the SeekBar (seekValue) and one for the TextView (seekDisplay)

    int mSeekValue;
    int mSeekDisplay;
    
    @Bindable
    public int getSeekValue() {
        return mSeekValue;
    }
    
    public void setSeekValue(int progress) {
        mSeekValue = progress;
        notifyPropertyChanged(BR.seekValue);
        setSeekDisplay(progress);
    }
    
    @Bindable
    public String getSeekDisplay() {
        return Integer.toString(mSeekDisplay);
    }
    
    public void setSeekDisplay(int progress) {
        mSeekDisplay = progress;
        notifyPropertyChanged(BR.seekDisplay);
    }
    

    Now you can bind these to the Widgets.

    
    
    

    The main point to note is that you are using two-way databinding on the SeekBar using @={viewModel.seekValue}, which will call your setSeekValue(...) method.

    One this is called, it will update your TextView by calling setSeekDisplay(...)

提交回复
热议问题