首页 > 解决方案 > 线程运行时按钮 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;
                }
            }
        }

任何帮助将不胜感激!谢谢你。

标签: javaandroidmultithreadingonclicklistener

解决方案


当你使用

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();

推荐阅读