1. 程式人生 > >記錄面試中的一道大意的題

記錄面試中的一道大意的題

連結:https://www.nowcoder.com/questionTerminal/ee6c0d0f043246bdb49d0b58d3aa7d15
來源:牛客網
 

閱讀程式碼回答執行結果

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

public classMainActivity extends Activity implements OnClickListener

{

   private Button mBtnLogin = (Button) findViewById(R.id.btn_login);

   private TextView mTextViewUser;

  

   @Override

   protected void onCreate(BundlesavedInstanceState)

   {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        mTextViewUser = (TextView) findViewById(R.id.textview_user);

        mBtnLogin.setOnClickListener(this);

        new Thread()

        {

            @Override

            public void run()

            {

                mTextViewUser.setText(10);

            }

        }.start();

   }

  

   @Override

   public void onClick(View v)

   {

        mTextViewUser.setText(20);

   }

}

A:Resources$NotFoundException

B:ViewRootImpl$CalledFromWrongThreadException

C:NullPointerException

D:執行正常,mTextViewUser元件上顯示內容為10

 

程式碼實測:

1、首先會報錯NullPointerException,就是privateButton mBtnLogin = (Button) findViewById(R.id.btn_login);這個位置,要先載入了layout後才能成功獲取到相應的按鈕元件物件;

2、修改NullPointerException錯誤後再執行,報錯 Resources$NotFoundException,在mTextViewUser.setText(10);這個位置(原本以為會先檢查onclick方法裡的setText(),但實際是run()裡的setText()),要改成字串形式;

3、修改上面的錯誤後再執行,報錯Resources$NotFoundException,這次就輪到mTextViewUser.setText(20);這個位置了;

4、修改上面的錯誤後再執行,沒有報錯,程式成功執行,點選按鈕後TextView由10變為20,說好的不能在非UI執行緒裡更新UI元件呢?翻看別人的部落格後,終於找到答案了,其實非UI執行緒是可以重新整理UI的,前提是它要擁有自己的ViewRoot,ViewRoot是在onResume()裡addview()建立的,所以是在 onResume()檢查是否為UI執行緒,一般在onCreate()中通過子執行緒可以更新UI,但官方不建議這樣做,因為 Android UI操作並不是執行緒安全的。

PS:而且,可以試下在上面程式碼的run()中setText()前加一句Thread.sleep(2000),先讓執行緒休眠個2到3秒,就會報錯 ViewRootImpl$CalledFromWrongThreadException,說明已經檢查到在非UI執行緒裡更新UI。