简体   繁体   中英

Dynamic text view in Android?

I am new to Android. I need to view one text on the screen. After thread sleep time I need to add another text on the screen. I have to show the text adding but my code display after all the append operation. How to show adding text one by one?

public class dynamictextview extends Activity {
    /** Called when the activity is first created. */
    private TextView tv ;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = new TextView(this);
        tv.setText("Dynamic Text View Test\n");
        setContentView(tv);
        for(int i=0;i<10;i++)
        {
            tv.setDrawingCacheBackgroundColor(MODE_APPEND);
            tv.append("\nAttempt "+i);
            try {
                Thread.sleep(500);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

The problem is that your Thread.sleep(500); is actually making the UI Thread to sleep. What you should do is that you should put the code of your for loop within another worker thread and make it run on the UI thread (runOnUIThread). I haven't tested it myself but theoretically the approach should work.

you can use handler's method postDelayed

  private TextView mTextView;
    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextView = (TextView) findViewById(R.id.textview);
        for(int i=0;i<10;i++)
        {

            handler.postDelayed(new ViewUpdater("\nAttempt "+i), 1000*i);

        }

    }
    private class ViewUpdater implements Runnable{
        private String mString;

        public ViewUpdater(String string){
            mString = string;
        }

        @Override
        public void run() {
          mTextView.append(mString);
        }
    }

First of all, you must not call Thread.sleep() from the UI thread.

Then to have the text appending behave as expected, you must first return from your onCreate() method before modifying the TextView's content.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM