gpt4 book ai didi

java - 如何在按下按钮后延迟一行代码

转载 作者:行者123 更新时间:2023-12-01 17:26:16 27 4
gpt4 key购买 nike

我是 Java 新手,正在尝试在用户按下按钮后延迟一行代码。该代码行递增一个数组,i++。我想这样做的原因是因为我通过淡入淡出两个 TextView 来为其设置动画。一个 textView 淡出,而另一个淡入,我试图通过仅在它们具有相同的 Alpha(动画设置持续时间的一半 500)后增加我的数组索引来更改正在显示的单词。我在网上查看过,我有看到一些建议使用 swing 计时器,还有一些建议使用 thread.sleep。有什么建议么?这是该按钮的代码:)。

public void nextWord(View view) { //nextWord is the onclick of the button


Button nextButton = findViewById(R.id.nextButton);
Button showTextButton = findViewById(R.id.showTextButton);
TextView wordTextView = findViewById(R.id.wordTextView);
EditText editTextView = findViewById(R.id.enterEditText);
ImageView logoImageView = findViewById(R.id.logoImageView);
TextView wordTextView1 = findViewById(R.id.wordTextView1);


i++; // need to delay this


String displayHint;
String displayText;

displayText = enterWord() + chooseArray();
displayHint = chooseArray();

wordTextView.setText(displayText);
editTextView.setHint(displayHint);
wordTextView1.setText(displayText) ;



enteredWords[i] = editTextView.getText().toString();

if (i%2 == 0) {
ObjectAnimator alphaAnimation = ObjectAnimator.ofFloat(wordTextView, View.ALPHA, 1f, 0f);
alphaAnimation.setDuration(1000);
ObjectAnimator otherAlphaAnimation = ObjectAnimator.ofFloat(wordTextView1, View.ALPHA, 0f, 1f);
otherAlphaAnimation.setDuration(1000);

AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(otherAlphaAnimation,alphaAnimation);
animatorSet.start();

} else {
ObjectAnimator alphaAnimation = ObjectAnimator.ofFloat(wordTextView, View.ALPHA, 0f, 1f);
alphaAnimation.setDuration(1000);
ObjectAnimator otherAlphaAnimation = ObjectAnimator.ofFloat(wordTextView1, View.ALPHA, 1f, 0f);
otherAlphaAnimation.setDuration(1000);

AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(otherAlphaAnimation,alphaAnimation);
animatorSet.start();
}


}

最佳答案

尝试使用

new Handler().postDelayed(Runnable r, long delay)

像这样使用

new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// fade in new text view
}
}, 1000); // time needed for first animation to finish

现在,当第一个动画需要 1000 毫秒完成时,第二个动画也会在 1000 毫秒后开始。您可以将其放入 final 值中以立即操纵这些延迟以保持它们同步

关于java - 如何在按下按钮后延迟一行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61204951/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com