Android basics: running code in the UI thread

后端 未结 7 601
悲&欢浪女
悲&欢浪女 2020-11-22 11:55

In the viewpoint of running code in the UI thread, is there any difference between:

MainActivity.this.runOnUiThread(new Runnable() {
    public void run() {
         


        
7条回答
  •  余生分开走
    2020-11-22 12:20

    If you need to use in Fragment you should use

    private Context context;
    
        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            this.context = context;
        }
    
    
        ((MainActivity)context).runOnUiThread(new Runnable() {
            public void run() {
                Log.d("UI thread", "I am the UI thread");
            }
        });
    

    instead of

    getActivity().runOnUiThread(new Runnable() {
        public void run() {
            Log.d("UI thread", "I am the UI thread");
        }
    });
    

    Because There will be null pointer exception in some situation like pager fragment

提交回复
热议问题