setText/setSeleted/invalidate控件閃退(崩潰)

搜了好多setText引發閃退/崩潰的解決方法,主要是這兩種:ide

  • setText需接字符串,不然將會按照id查找相應字符,若輸入的是數字,則默認認爲是id,當查找不到相應字符的id時就會崩潰。
  • 被setText修改的控件佈局與當前佈局不一樣,沒有加載控件的佈局。

可是我拿到的這個程序不符合上面的兩種錯誤,後來把崩潰點日誌拿給大神看了一下,大神說Only the original thread that created a view hierarchy can touch its views是由於在安卓中只有兩種線程,UI線程(主線程)和Worker線程,在非UI線程中不能進行UI操做佈局

看了看三個崩潰點,都在callback裏面,可不就是都在非UI線程裏面麼……post

修改的方法:使用post向UI線程請求UI操做線程

a) 原代碼日誌

String totalStr = Utility.byte2XB((total << 20));
String freeStr = Utility.byte2XB((free << 20));
tvRouterStorage.setText(getString(R.string.router_download_store, totalStr, freeStr));

b) 修復後代碼code

totalStr和freeStr定義爲類對象
totalStr = Utility.byte2XB((total << 20));
freeStr = Utility.byte2XB((free << 20));
tvRouterStorage.post(new Runnable() {
    @Override
    public void run() {
        tvRouterStorage.setText(getString(R.string.router_download_store, totalStr, freeStr));
    }
});
相關文章
相關標籤/搜索