如何在 Android 中为文本创建计数效果查看

2022-09-02 04:58:35

我正在开发一个应用程序,该应用程序可以计算几段文本中的问号数量。

扫描完成后(这根本不需要时间),我希望在数字从0变为TOTAL后显示总数。因此,对于 10:0,1,2,3,4,5,6,7,8,9 10,然后停止。

我尝试了几种不同的技术:

                TextView sentScore = (TextView) findViewById(R.id.sentScore);

                long freezeTime = SystemClock.uptimeMillis();

                for (int i = 0; i < sent; i++) {
                    if ((SystemClock.uptimeMillis() - freezeTime) > 500) {
                        sentScore.setText(sent.toString());
                    }
                }

我也试过这个:

    for (int i = 0; i < sent; i++) { 
        // try {
            Thread.sleep(500);

        } catch (InterruptedException ie) {
            sentScore.setText(i.toString()); 
        } 
    }

我相信这些都是完全业余的尝试。任何帮助将不胜感激。

谢谢

理查


答案 1

我为此使用了更传统的Android风格动画:

        ValueAnimator animator = new ValueAnimator();
        animator.setObjectValues(0, count);
        animator.addUpdateListener(new AnimatorUpdateListener() {
            public void onAnimationUpdate(ValueAnimator animation) {
                view.setText(String.valueOf(animation.getAnimatedValue()));
            }
        });
        animator.setEvaluator(new TypeEvaluator<Integer>() {
            public Integer evaluate(float fraction, Integer startValue, Integer endValue) {
                return Math.round(startValue + (endValue - startValue) * fraction);
            }
        });
        animator.setDuration(1000);
        animator.start();

您可以使用 和 值使计数器从任意数字变为任意数字,并使用 和 设置整个动画的持续时间。0count1000

请注意,这支持Android API级别11及以上,但您可以使用令人敬畏的nineoldandroids项目使其轻松向后兼容。


答案 2

试试这个:

private int counter = 0;
private int total = 30; // the total number
//...
//when you want to start the counting start the thread bellow.
    new Thread(new Runnable() {

                public void run() {
                    while (counter < total) {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        t.post(new Runnable() {

                            public void run() {
                                t.setText("" + counter);

                            }

                        });
                        counter++;
                    }

                }

            }).start();

推荐