【问题标题】:How to delay a line of code after a button press按下按钮后如何延迟一行代码
【发布时间】:2023-03-25 00:03:01
【问题描述】:

我是 Java 新手,我试图在用户按下按钮后延迟一行代码。这行代码增加了一个数组,i++。我想这样做的原因是因为我正在通过淡化它们来为两个 textView 设置动画。一个 textView 淡出,而另一个淡入,我试图通过仅在它们具有相同的 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】:

    试试

    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 值中,以立即操纵这些延迟以保持它们同步

    【讨论】:

      猜你喜欢
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-14
      • 1970-01-01
      • 2014-03-01
      • 1970-01-01
      • 2015-07-11
      相关资源
      最近更新 更多