java - 线程运行时按钮 onClick() 不起作用
问题描述
我正在努力设置 TextView 的文本,所以我现在尝试通过按钮按下来完成,但是当我从按钮启动线程时,readWeight
按钮updateButton
不起作用。
这是我的两个按钮onClick
方法:
readWeight.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
inputWindow.setText("helloooooooo worldddddd");
//connector.run();
System.out.println("********** PRINTING **********");
// readWeight.setVisibility(View.INVISIBLE);
}
});
updateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("!!!!!!!!!!!!!!!"+weight+"!!!!!!!!!!!!!!!");
inputWindow.setText(weight);
}
});
这是我启动线程的方法,这个方法在另一个类中:
public void run() {
new Handler().post(new Runnable() {
@Override
public void run() {
// Always cancel discovery because it will slow down a connection
//Log.d("workkkkkk","$$$$$$$$$$$$$$$$****** printingggggg ******$$$$$$$$$$$$$$$$");
int counter = 0;
while (true) {
counter++;
try {
output = "";
//read the data from socket stream
//mmInStream != null && counter%10000000 == 1
if (mmInStream != null) {
mmInStream.read(buffer);
for (byte b : buffer) {
char c = (char) b;
if (c >= ' ' && c < 'z') {
// System.out.print(c);
output += c;
}
}
System.out.println();
Intent intent = new Intent();
intent.setAction("com.curie.WEIGHT_RECEIVED");
intent.putExtra("Output",output);
if (counter % 10 == 0) {
System.out.println(counter);
//InputActivity.setInputWindowText(output);
LocalBroadcastManager.getInstance(InputActivity.getContext()).sendBroadcastSync(intent);
}
}
// Send the obtained bytes to the UI Activity
} catch (IOException e) {
//an exception here marks connection loss
//send message to UI Activity
break;
}
}
}
任何帮助将不胜感激!谢谢你。
解决方案
当你使用
Handler.post()
它在 UI 线程中运行,因此如果它是长动作,它将阻塞所有界面。为避免它,您应该在另一个线程中运行它。如果你不想使用复杂的东西,你可以试试这个:
mHandler = new Handler();
new Thread(new Runnable() {
@Override
public void run () {
mHandler.post(new Runnable() {
@Override
public void run () {
// place your action here
}
});
}
}).start();
推荐阅读
- java - 如何正确连接 HiveMQ 中的身份验证?
- powershell - 如何更改此powershell脚本以取消选中“允许计算机关闭此设备以节省电源”以除以太网之外的Wi-Fi
- javascript - 在窗口滚动上添加和删除类
- sas - 如何根据匹配日期对数据进行子集化和设置值
- python - 如何优化代码以制作基于 Pandas 列值垂直堆叠的列表?
- javascript - 无法将文件上传到 Firebase 存储
- spring-boot - JWT 在不同的成功登录用户中成功验证
- c - 在ubuntu中编译ac程序后的可执行文件在哪里?
- angularjs - Angularjs:使用 ng-if 过滤 ng-repeat
- fullcalendar - Fullcalendar 使用资源作为选择菜单的功能