In my android application I am trying to show a "Loading..." text which will change every 100 ms. After every 100 milliseconds it will increase one dot. So first it will be like "Loading." and the after another 100 ms it will be "Loading.." When it will be "Loading..." , this process will terminate and again start from the first on words. It will continue till 3500 ms. It will be pretty like progress bar.
I hope I am able to explain the problem.
How to resolve this problem? Please help.
4 Answers
Not the best answer, but it works.
Handler handler = new Handler(); for (int i = 100; i <= 3500; i=i+100) { handler.postDelayed(new Runnable() { @Override public void run() { if(i%300 == 0){ textView.setText("Loading."); }else if(i%200 == 0){ textView.setText("Loading.."); }else if(i%100 == 0){ textView.setText("Loading..."); } } }, i); } 3Kotlin Snippet for Animating (Loading...):
ValueAnimator.ofInt(0, 4).apply { repeatCount = 10 duration = 1000 addUpdateListener { valueAnimator -> val dotsCount = valueAnimator.getAnimatedValue() as Int if (dotsCount < 4) { spannable.setSpan(transparentColorSpan, 7 + dotsCount, 10, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) textView.invalidate() } } }.start() 3A CountdownTimer seems to fit, change the text in onTick.
You should use an AsyncTask. This class is meant to do long-running background tasks that will publish updates and run on the UI thread automatically.
In doInBackground, have your loop that will then call publishProgress which will call onProgressUpdate every 100ms with the new values.
This will be done in the background and onProgressUpdate will run on the UI thread for you automatically.
Something on the lines of:
private class ShowLoading extends AsyncTask<Void, Integer, Void> { @Override protected Void doInBackground(Void... params) { for (int i = 0; i < 3500; i++){ publishProgress(i); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; } @Override protected void onProgressUpdate(Integer... values) { // TODO Auto-generated method stub super.onProgressUpdate(values); if (values[0]%3 == 0){ textview.setText ("Loading."); } else if (values[0]%3 == 1){ textview.setText ("Loading.."); } else if (values[0]%3 == 2){ textview.setText ("Loading.."); } } } 1