Can you set textview text within a thread?

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-06 15:43:44

问题


What I need it to have it once the app stops reciving text from the server saying that it is now disconected I need to set the button to say that it is disconnected, this is what I have right now (this is in a while loop I just didnt post all of the code)

Thread.sleep(10);
                        counter++;
                        if (counter >= 100)
                        {
                            Log.d("ClientActivity","send S");
                            counter = 0;
                            out.println("S");
                            A2MCString = in.readLine();
                            Log.d("ClientActivity","got " + A2MCString);
                            if (A2MCString == null) 
                                {
                                connected = false;
                                Log.d("ClientActivity","Closed1");
                                Connect.setText("Connect");
                                Log.d("ClientActivity","Closed2");
                                Connect.setBackgroundResource(R.drawable.contect_button);
                                Log.d("ClientActivity","Closed3");
                                DeBug.setText("Disconnected from " + serverIpAddress);
                                Log.d("ClientActivity","Closed4");
                                }

the app crashes when I try to set connect to "Connect" the logCat error is "android.view.ViewRoot$CalledFromWrongThreadException" If you could help me it would be great!


回答1:


Use runOnUiThread or a handler to make changes to UI from a thread.. I think this line is causing the error..

Connect.setBackgroundResource(R.drawable.contect_button);

put it in runOnUiThread in your thread like this

       runOnUiThread(new Runnable() {
                     public void run() {

                        Connect.setBackgroundResource(R.drawable.contect_button);
                    }
                });


来源:https://stackoverflow.com/questions/10374519/can-you-set-textview-text-within-a-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!