延迟时如何启用按钮

时间:2018-11-01 15:58:23

标签: java android android-studio

我想在有人按下开关时启用一个按钮。 这是我到目前为止的内容:

public class MainActivity extends AppCompatActivity {
    int num = 1;
    String pre = "";
    Date currentTime = Calendar.getInstance().getTime();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        changeTextViewToDate();

    }

    private void changeTextViewToDate() {

        Button steve = findViewById(R.id.nicememe);
        final TextView job = findViewById(R.id.MainDisplay);
        steve.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Switch simpleSwitch = (Switch) findViewById(R.id.emergency);
                Boolean switchState = simpleSwitch.isChecked();
                if (switchState == false) {
                    {
                        ((Button) findViewById(R.id.nicememe)).setEnabled(false);

                        new Handler().postDelayed(new Runnable() {

                            @Override
                            public void run() {
                                ((Button) findViewById(R.id.nicememe)).setEnabled(true);

                            }
                        }, 3000);
                    }
                    job.setText(pre + Integer.toString(num) + " " + Calendar.getInstance().getTime() + System.getProperty("line.separator"));
                    job.setMovementMethod(new ScrollingMovementMethod());
                    num++;
                    String now = job.getText().toString();
                    pre = now;
                }
                else {
                    ((Button) findViewById(R.id.nicememe)).setEnabled(true);
                    job.setText(pre + Integer.toString(num) + " " + Calendar.getInstance().getTime() + " EMERGENCY" + System.getProperty("line.separator"));
                    job.setMovementMethod(new ScrollingMovementMethod());
                    num++;
                    String now = job.getText().toString();
                    pre = now;
                }

            }
        });
    }
}

发生了什么事,该按钮已被禁用,但是当我按下开关时,它仍处于禁用状态。只有在开关打开的情况下,我才能快速按下按钮。我希望这样,即使在有人紧急接通时延迟的情况下,也可以再次按下该按钮。这可能吗?

1 个答案:

答案 0 :(得分:0)

这不是从另一个线程执行UI操作的正确方法。每当您从另一个线程执行UI操作时,请调用runOnUiThread。像这样:

number_disks = -2

try:
      number_disks > 0 and number_disks <= 8
      print("Perfect")
except:
      print("the number of disks is between 1 and 8, try again!")
      number_disks = input(int("what is the number of disks?\n"))