How to set text of text view in another thread

后端 未结 4 1502
说谎
说谎 2020-11-30 07:42

I am tring to setText in another thread, that is, child thread. But for the following code, it is giving the error

Only the original thread that creat

相关标签:
4条回答
  • 2020-11-30 08:15

    Either you can use runOnUiThread or use Handler to set text in TextView.

    0 讨论(0)
  • 2020-11-30 08:19

    Use runOnUiThread for updating the UI control. In your case:

    runningActivity.runOnUiThread(new Runnable() {
        public void run() {
            tv.setText(p + " %");
        }
    });
    

    Edited:

    Activity mActivity;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        mActivity= this;
       ...
       ..//The rest of the code
    } //close oncreate()
    
    thread{
        mActivity.runOnUiThread(new Runnable() {
            public void run() {
                tv.setText(p + " %");
            }
        });
    }
    
    0 讨论(0)
  • 2020-11-30 08:20

    You need a reference to that textview and then do:

    textView.post(new Runnable() {
        public void run() {
            textView.setText(yourText);
        } 
    });
    
    0 讨论(0)
  • 2020-11-30 08:27

    You can use handle :

    handler.post(new Runnable() {
        public void run() {
            textView.setText(yourText);
        }
    });
    

    But your textView and yourText must be class fields.

    In your thread (activity) where you create textView use:

    Handler handler = new Handler();
    

    And pass handler into another thread.

    0 讨论(0)
提交回复
热议问题