databinding的使用之数据动态改变刷新UI
作者:互联网
android { 。。。 dataBinding { enabled = true } 。。。 }
通过以上方式开始可以使用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(); } }
运行代码,效果如下
文本会一直变化
标签:int,price,amount,UI,void,interest,刷新,databinding,public 来源: https://www.cnblogs.com/androidstudyrecord/p/14711635.html