我在android中有处理程序的问题,我不明白不显示结果,这是代码:
public class Main extends Activity implements OnClickListener {
private EditText nhap;
private Button btTinh;
private Button btHuy;
private TextView kq;
private ProgressDialog progress;
private Handler handle = new Handler();
private int count = 0;
private String s = "";
private long n;
的handleMessage:
Handler mhandle = new Handler() {
@Override
public void handleMessage(Message msg) {
kq.setText(msg.obj.toString());
}
};
的onCreate:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
nhap = (EditText) findViewById(R.id.nhap);
btTinh = (Button) findViewById(R.id.btTinh);
btHuy = (Button) findViewById(R.id.btHuy);
kq = (TextView) findViewById(R.id.kq);
btTinh.setOnClickListener(this);
btHuy.setOnClickListener(this);
}
public boolean checkPrime(long n) {
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0)
return false;
}
return true;
}
outprime:
public void outPrime(long t) {
// String s="";
progress.setCancelable(true);
progress.setMessage("File downloading ...");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setProgress(0);
progress.setMax(Integer.parseInt(nhap.getText().toString()));
progress.show();
n = t;
new Thread() {
public void run() {
for (int i = 2; i < n; i++) {
count = i;
if (checkPrime(i))
s = s + i + " ";
handle.post(new Runnable() {
public void run() {
// TODO Auto-generated method stub
progress.setProgress(count);
}
});
}
if (count == n - 1) {
progress.dismiss();
Message msg = handle.obtainMessage(1, (String)s);
handle.sendMessage(msg);
}
}
}.start();
}
的onclick:
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btTinh:
progress = new ProgressDialog(this);
outPrime(Long.parseLong(nhap.getText().toString()));
break;
case R.id.btHuy:
nhap.setText("");
break;
}
}}
这是handlemessage:
Handler mhandle = new Handler() {
@Override
public void handleMessage(Message msg) {
kq.setText(msg.obj.toString());
}
};
我不明白handlemessage不返回值,“kq.setText(msg.obj.toString());”不显示到屏幕,抱歉,因为我的英语不好
答案 0 :(得分:1)
我认为你的问题的答案是“注意你变量的名字!”看 - 你创建了2个处理程序 - 名为“mhandle”和“handle”。您想在Handler中解析名为“mhandle”的消息,但在您的Thread中将其发送到“handle”,这对您的代码没有任何作用。 希望如果你仍然想找到答案,它会有所帮助。