databinding的使用之数据动态改变刷新UI

android {
    。。。

    dataBinding {
        enabled = true
    }

  
    。。。
   
}

 

databinding的使用之数据动态改变刷新UI

 

通过以上方式开始可以使用databinding

 

public class Bitcoin extends BaseObservable {  //记得继承BaseObservable
    public int price;
    public int amount_of_interest;

    @Bindable
    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
        notifyPropertyChanged(BR.price);   //注意:未转换布局BR是引用不到price的
    }

    @Bindable
    public int getAmount_of_interest() {
        return amount_of_interest;
    }

    public Bitcoin(int price, int amount_of_interest) {
        this.price = price;
        this.amount_of_interest = amount_of_interest;
    }

    public void setAmount_of_interest(int amount_of_interest) {
        this.amount_of_interest = amount_of_interest;
    }
}

 

public class MainActivity extends AppCompatActivity {
    private Bitcoin bitcoin;
    private  int i = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityMainBinding activityMainBinding = DataBindingUtil.setContentView(this,R.layout.activity_main);
        bitcoin = new Bitcoin(0,0);
        activityMainBinding.setBitcoin(bitcoin);//注意:必须在xml里使用了bitcoin,这里才能调用setBitcoin方法
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (i % 5 == 0) {
                                bitcoin.setPrice((int) System.currentTimeMillis());
                            }
                        }
                    });

                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();



    }
}

运行代码,效果如下

 

 

 databinding的使用之数据动态改变刷新UI

 

 

 文本会一直变化

上一篇:easy ui Uncaught Error: cannot call methods on tooltip prior to initialization; attempted to call method 'hide'


下一篇:怎样通俗易懂理解WPF的 DataBinding(抓住关键核心)