user3320405
user3320405

Reputation:

count-up effect for a textView in Android

I am working on an app that counts the number of words in a paragraphs/page of text.

After the scanning is done, I would love to show the output total number of words after the number goes from 0 to TOTAL (No of Words).

Example: So, for 100 words: 0..wait..1..wait..2..wait..3..wait..4..wait..5,6,7,8,9 10.......99,100 and then STOP.

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

But nothing is helped me. I am sure these are both completely amateur attempts.

Any help? Thanks

Upvotes: 0

Views: 591

Answers (2)

Vishwajit Palankar
Vishwajit Palankar

Reputation: 3103

The below code will help you current gap is 100 ms but you can change as per your convenience

for (int i = 0; i < sent; i++) {
        new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            sentScore.setText(sent.toString());
        }
    }, 100 * i);
}

Upvotes: 2

vktr
vktr

Reputation: 149

In android you are supposed to use AsyncTask for this kind of work

http://developer.android.com/reference/android/os/AsyncTask.html

private class CountUpTask extends AsyncTask<Void, Void, Void> {

    private TextView textview;
    private int current, total, interval;

    public CountUpTask(TextView textview, int total, int interval) {
        this.textview = textview;
        this.current = 0;
        this.total = total;
        this.interval = interval;
    }

    @Override
    protected void doInBackground() {
        while(this.current < this.total){
          Thread.sleep(this.interval);
          this.current++;
          publishProgress(this.current);
        }

        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        this.textview.setText("0");
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
        this.textview.setText(progress+"");
    }

    @Override
    protected void onPostExecute() {

    }
}

As you can see, doInBackground is executed in a background thread, onPrexcute, onProgressUpdate and onPostExecute are executed in UI thread, allowing you to update the UI.

CountUpTask countUpTask = new CountUpTask ((TextView) findViewById(R.id.sentScore), sent, 500);
countUpTask.execute();

Upvotes: -1

Related Questions