Java 如何在android中设置延迟?
但它只会变为黑色。请尝试以下代码:Java 如何在android中设置延迟?,java,android,Java,Android,但它只会变为黑色。请尝试以下代码: Thread timer = new Thread() { public void run(){ try { buttons[inew][jnew].setBackgroundColor(Color.BLACK); sleep(5000); } catch (Inter
Thread timer = new Thread() {
public void run(){
try {
buttons[inew][jnew].setBackgroundColor(Color.BLACK);
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
timer.start();
buttons[inew][jnew].setBackgroundColor(Color.WHITE);
使用
Thread.sleep(millis)
方法。您可以使用CountDownTimer
,这比发布的任何其他解决方案都要高效。您还可以使用它的onTick(long)
方法定期生成通知
请看这个显示30秒倒计时的示例
import android.os.Handler;
...
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Do something after 5s = 5000ms
buttons[inew][jnew].setBackgroundColor(Color.BLACK);
}
}, 5000);
如果您想在UI中定期执行某些操作,最好使用倒计时:
new CountDownTimer(30000, 1000) {
public void onFinish() {
// When timer is finished
// Execute your code here
}
public void onTick(long millisUntilFinished) {
// millisUntilFinished The amount of time until finished.
}
}.start();
如果您经常在应用程序中使用延迟,请使用此实用程序类
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
用法:
import android.os.Handler;
public class Utils {
// Delay mechanism
public interface DelayCallback{
void afterDelay();
}
public static void delay(int secs, final DelayCallback delayCallback){
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
delayCallback.afterDelay();
}
}, secs * 1000); // afterDelay will be executed after (secs*1000) milliseconds.
}
}
您可以使用以下选项:
// Call this method directly from java file
int secs = 2; // Delay in seconds
Utils.delay(secs, new Utils.DelayCallback() {
@Override
public void afterDelay() {
// Do something after delay
}
});
对于延迟本身,添加:
import java.util.Timer;
其中,
延迟
变量以毫秒为单位;例如,将延迟设置为5000,延迟5秒。处理程序在Kotlin中回答:
1-在文件内创建一个文件(例如,包含所有顶级函数的文件):
2-然后在任何需要的地方调用它:
fun delayFunction(function: ()-> Unit, delay: Long) {
Handler().postDelayed(function, delay)
}
这里有一个例子,我用2秒的alpha淡入延迟将背景图像从一个更改为另一个,双向-将原始图像淡入2秒淡入2秒淡入
delayFunction({ myDelayedFunction() }, 300)
我认为到2020年,最简单、最稳定、最有用的方法是使用delay
函数而不是Runnable。协同路由是处理异步作业的一个好概念,它的延迟
组件将是这个答案的重点
警告:协同程序需要Kotlin语言,我没有将代码转换为Kotlin,但我认为每个人都能理解主要概念
只需在您的build.gradle
上添加协同程序:
public void fadeImageFunction(View view) {
backgroundImage = (ImageView) findViewById(R.id.imageViewBackground);
backgroundImage.animate().alpha(0f).setDuration(2000);
// A new thread with a 2-second delay before changing the background image
new Timer().schedule(
new TimerTask(){
@Override
public void run(){
// you cannot touch the UI from another thread. This thread now calls a function on the main thread
changeBackgroundImage();
}
}, 2000);
}
// this function runs on the main ui thread
private void changeBackgroundImage(){
runOnUiThread(new Runnable() {
@Override
public void run() {
backgroundImage = (ImageView) findViewById(R.id.imageViewBackground);
backgroundImage.setImageResource(R.drawable.supes);
backgroundImage.animate().alpha(1f).setDuration(2000);
}
});
}
将作业添加到类(活动、片段或其他内容),您将在其中使用协同程序:
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9'
您可以通过使用launch{}body在类的任何地方使用协同程序。因此,您可以这样编写代码:
private var job: Job = Job()
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job
public void onClick(View v) {
launch {
switch(v.getId()) {
case R . id . rollDice :
Random ranNum = new Random();
int number = ranNum . nextInt (6) + 1;
diceNum.setText("" + number);
sum = sum + number;
for (i= 0;i < 8;i++){
for (j= 0;j < 8;j++){
int value =(Integer) buttons [i][j].getTag();
if (value == sum) {
inew = i;
jnew = j;
buttons[inew][jnew].setBackgroundColor(Color.BLACK);
delay(2000)
buttons[inew][jnew].setBackgroundColor(Color.WHITE);
break;
}
}
}
break;
}
}
}
因此,如果希望所有for循环等待delay
,那么,launch{}
应该覆盖for循环
launch{}
的另一个好处是,您正在使for循环异步,这意味着它不会在繁重的进程上阻塞应用程序的主UI线程。不要在UI线程上执行此操作——其他元素也可能停止响应,稍后会因警告而表现出不可预测的行为。这正是我需要的,延迟UI线程。完美满足我的需求。谢谢。这个解决方案解释了我在一些代码行中遇到的所有问题。我总是回到这篇文章,因为我太懒了,每次都写不出来。谢谢。很好,但我有很多信息要等,然后再看。所以多重踏板会带来问题。如何解决多步问题此解决方案会产生内存泄漏,因为它使用了一个非静态的内部匿名类,该类隐式地包含对其外部类activity的引用。有关更好的解决方案,请参阅。@EugeneH使用活动模板以简化生活为什么?这是纯粹的开销和复杂性。。。毫无疑问,如果我们使用频繁的延迟,那么有一个固定的延迟格式就可以了。我认为,由于增加了一个接口和一个方法,不会有太多开销。它比处理程序更干净。
private var job: Job = Job()
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job
public void onClick(View v) {
launch {
switch(v.getId()) {
case R . id . rollDice :
Random ranNum = new Random();
int number = ranNum . nextInt (6) + 1;
diceNum.setText("" + number);
sum = sum + number;
for (i= 0;i < 8;i++){
for (j= 0;j < 8;j++){
int value =(Integer) buttons [i][j].getTag();
if (value == sum) {
inew = i;
jnew = j;
buttons[inew][jnew].setBackgroundColor(Color.BLACK);
delay(2000)
buttons[inew][jnew].setBackgroundColor(Color.WHITE);
break;
}
}
}
break;
}
}
}
launch{
buttons[inew][jnew].setBackgroundColor(Color.BLACK);
delay(2000)
buttons[inew][jnew].setBackgroundColor(Color.WHITE);
}