按下按钮后每1.5秒调用一次函数

时间:2019-01-04 23:00:37

标签: java android

我现在创建的函数每次在我的android应用程序中单击一个按钮时都会给我一个0.8到1.2之间的随机数,并在TextView中显示结果。但是,对于此功能,我希望每1.5秒为我提供一个新数字,而不必连续单击按钮以获取新结果。我将如何去做呢?

下面显示了我想每1.5秒调用一次的函数。

public void generate(View view) {
    double min = 0.8;
    double max = 1.2;
    Random rand = new Random();
    double number = rand.nextDouble()* max;
    TextView myText = (TextView)findViewById(R.id.textView_RanNum);
    String myString = String.valueOf(number);
    myText.setText(myString);
}

所有帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

您可以使用Handler / Runnable:

public class MainActivity extends AppCompatActivity {

Handler handler;
Button buttonStart, buttonStop;

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

    handler = new Handler();
    buttonStart = findViewById(R.id.button);
    buttonStop = findViewById(R.id.button2);

    buttonStart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            runnable.run();
        }
    });
    buttonStop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            handler.removeCallbacks(runnable);
        }
    });

}

public Runnable runnable = new Runnable() {
    public void run() {
        generate();
        handler.postDelayed(runnable, 1500); // 1500 miliseconds
    }};

public void generate() {
    double min = 0.8;
    double max = 1.2;
    double number;
    Random rand = new Random();
    TextView myText = findViewById(R.id.textView_RanNum);

    number = rand.nextDouble() * max;
    String myString = String.valueOf(number);
    myText.setText(myString);
  }

}

答案 1 :(得分:0)

您可以使用Android的Handler类执行此操作。

public class MainActivity extends AppCompatActivity {
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Handler myHand = new Handler();
                myHand.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                      generate();
                    }
                }, 1500);
            }
        });
    }

    public void generate() {
        double min = 0.8;
        double max = 1.2;
        Random rand = new Random();
        double number = rand.nextDouble() * max;
        TextView myText = (TextView) findViewById(R.id.textView_RanNum);
        String myString = String.valueOf(number);
        myText.setText(myString);
    }
}

在此处了解有关处理程序的更多信息:https://developer.android.com/reference/android/os/Handler