如何在启动线程时更改按钮文本?

时间:2017-10-12 16:11:02

标签: java android

我在onCreate类的MainACtivity方法中有这段代码:

setContentView(R.layout.activity_main);

Button button1 = (Button)findViewById(R.id.button1);
button1.setText("Start");

final baresipThread thread = new baresipThread();

button1.setOnClickListener(new View.OnClickListener() {
    boolean running = false;
    @Override
    public void onClick(View v) {
        if (!running) {
            ((Button)v).setText("Stop");
            thread.start();
            running = true;
        } else {
            thread.kill();
            running = false;
            ((Button)v).setText("Start");
        }
    }
});

和baresipThread类看起来像这样:

package com.tutpro.baresip;

public class baresipThread extends Thread {

    public void run() {
        baresip_start();
    }

    public void kill() {
        baresip_kill();
    }

    public native void baresip_start();
    public native void baresip_kill();

}

如果我从代码中删除了thread.start() / thread.kill()个来电,那么按下该按钮的文字会在每次按下时切换。但是如果包含了线程调用,那么当我按下它时,按钮的文本(最初Start)没有变化。线程启动正常。

为什么文本没有改变以及如何实现?

1 个答案:

答案 0 :(得分:0)

使用以下代码

 final boolean running = false;
    final baresipThread thread = new baresipThread();
    button1.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        if (!running) {
            ((Button)v).setText("Stop");
            thread.start();
            running = true;
        } else {
            thread.kill();
            running = false;
            ((Button)v).setText("Start");
        }
    }
});