作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 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/
我是一名优秀的程序员,十分优秀!