我在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;


句柄消息:

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;
}


超越:

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;
    }
}}


这是句柄消息:

Handler mhandle = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        kq.setText(msg.obj.toString());
    }
};


我不明白handlemessage不返回值,“ kq.setText(msg.obj.toString());”不显示在屏幕上,对不起,因为我的英语不好

最佳答案

我认为您问题的答案是“当心变量名称!”看-您已经创建了2个处理程序-分别名为“ mhandle”和“ handle”。您想在名为“ mhandle”的处理程序中解析消息,但在线程中将其发送到“ handle”,这对您的代码无济于事。
希望如果您仍在尝试找到答案,它将对您有所帮助。

08-06 22:37