我不明白为什么 setText
对 TextView
没有任何作用,而且我似乎根本没有收到任何错误。
我尝试设置文本的原因之一是我想查看是否成功与服务器建立了连接。
这是我的代码:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText textField = findViewById(R.id.textField);
final Button submitBtn = findViewById(R.id.submitBtn);
final TextView debugLbl = findViewById(R.id.debugLbl);
final TextView debug2Lbl = findViewById(R.id.debug2);
submitBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String text = textField.getText().toString();
textField.setText("");
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
try {
Socket socket = new Socket("10.0.2.2", 9723);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(text);
bw.flush();
debug2Lbl.setText("Successfully sent message : "+ text + " to server");
socket.close();
} catch (Exception e) {
e.printStackTrace();
debugLbl.setText("error");
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
});
}
}
最佳答案
您正在非 UI 线程上操作 View 。相反,您应该使用 AsyncTask
或调用 debug2Lbl.post
方法将更改注入(inject)到 UI 线程上。
关于java - TextView setText() 不执行任何操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50668810/