Java 如何在Android中为textView创建计数效果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9736940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:54:39  来源:igfitidea点击:

How to create a count-up effect for a textView in Android

javaandroidandroid-layout

提问by Richard Burton

I am working on an app that counts the number of questions marks in a few paragraphs of text.

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

After the scanning is done (which takes no time at all) I would love to have the total presented after the number goes from 0 to TOTAL. So, for 10: 0,1,2,3,4,5,6,7,8,9 10and then STOP.

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

I have tried a couple of different techniques:

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

                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());
                    }
                }

Also I tried this:

我也试过这个:

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

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

I am sure these are both completely amateur attempts. Any help would be much-appreciated.

我确信这些都是完全业余的尝试。任何帮助将非常感激。

Thanks,

谢谢,

Richard

理查德

采纳答案by Luksprog

Try this:

尝试这个:

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();

回答by Magicode

Maybe try changing the for loop to something like:

也许尝试将 for 循环更改为:

int count = 0;
while (count != sent) {
    if ((SystemClock.uptimeMillis() - freezeTime) > 500) {
        count++;
        sentScore.setText("" + count);
        freezeTime = SystemClock.uptimeMillis();
    }
}

回答by Shubhayu

Use a worker thread to do the waiting and update your UI thread.

使用工作线程进行等待和更新您的 UI 线程。

You could use an AsyncTask, though it might be an overkill for this job. If you use this, In the doInBackground() loop over the number of sleep periods and after every sleep period, update the count in the UIthread.

您可以使用 AsyncTask,尽管这对于这项工作来说可能有点矫枉过正。如果你使用它,在 doInBackground() 循环中的睡眠周期数和每个睡眠周期之后,更新 UIthread 中的计数。

There you go! Slukain just gave you the working code :P

你去吧!Slukain 刚刚给了你工作代码:P

回答by Pavandroid

Use TextSitcher

使用TextSitcher

for the best effects. It will transform the text softly.

以获得最佳效果。它将轻柔地转换文本。

When coming to the change of the text use the below Code.

当要更改文本时,请使用以下代码。

> int number = 0;
>         Timer obj = new Timer();
>         TimerTask tt = new TimerTask() {
>                       @Override           public void run() {
>               // TODO Auto-generated method stub
>               textView.setText(number++);
>               if(number < score)
>               obj.schedule(tt, 200);          }       };
>         obj.schedule(tt, 200);

回答by marmor

I've used a more conventional Android-style animation for this:

为此,我使用了更传统的 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();

You can play with the 0and countvalues to make the counter go from any number to any number, and play with the 1000to set the duration of the entire animation.

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

Note that this supports Android API level 11 and above, but you can use the awesome nineoldandroidsproject to make it backward compatible easily.

请注意,这支持 Android API 级别 11 及更高级别,但您可以使用很棒的Nineoldandroids项目使其轻松向后兼容。

回答by AnujDeo

The question is very old, but I am posting this so that it would help someone else. I have used these 2 amazing libraries.

这个问题很老了,但我发布这个是为了帮助别人。我用过这两个很棒的库。

Try them

试试看

  1. https://github.com/MasayukiSuda/CountAnimationTextView
  1. https://github.com/MasayukiSuda/CountAnimationTextView

Sample Effect

示例效果

Or 2. https://github.com/robinhood/ticker

或 2. https://github.com/robinhood/ticker

Sample effect of 2nd library

第二个库的示例效果

Hope this helps :) Happy Coding!!!

希望这会有所帮助:) 快乐编码!!!