databinding的使用之數據動態改變刷新UI

android {
    。。。

    dataBinding {
        enabled = true
    }  
    。。。   }

 

 

經過以上方式開始可使用databindinghtml

 

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();



    }
}

運行代碼,效果以下android

 

 

 

 

 

 文本會一直變化ide

相關文章
相關標籤/搜索