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

问题描述 投票:0回答:1

我是Java新手,正在尝试在用户按下按钮后延迟一行代码。该行代码增加了数组[[i ++。我想这样做的原因是因为我正在通过使两个textView动画化。一个textView淡出,而另一个text淡入,我试图通过仅增加数组索引来改变显示的单词,因为它们具有相同的Alpha,即动画设置持续时间500的一半。看到有人建议使用swing timer,而另一些建议使用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(); } }
java android button textview delay
1个回答
0
投票
尝试使用

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值中,以立即操纵这些延迟以使其保持同步
© www.soinside.com 2019 - 2024. All rights reserved.