Display Values Dynamically in TextView - Android

喜你入骨 提交于 2019-12-12 06:37:55

问题


I have a simple program with one button. Once I clicked on the button loop started and should display the current value in TextView dynamically. But this display the value when loop is completed.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); 
    tv=(TextView) findViewById(R.id.textView2);
}

public  void btnClick(View v) throws Exception {

    for (int i=0;i<10;i++){
    tv.setText("Value of I "+i);
    Thread.sleep(500);
    }
}

My expected output is displaying values from 0, 1,.... dynamically but displayed 9 at last. if I use append I have to wait until loop terminated. Please help me.


回答1:


Try this:

int i = 0; //declare this globally
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        if(i != 10) { 
                text.append(" " + i);
                i++;
                handler.postDelayed(this, 1000);
            }
        }
    }, 1000);
}

Make sure you declare int i = 0 globally




回答2:


tv.append("text here") is your answer.




回答3:


don't use Thread.sleep() in your main UI thread this should give an exception instead use a new Thread like this

Thread myThread = new Thread(new Runnable() {

        @Override
        public void run() {
            for (int i=0;i<10;i++){
                          tv.setText("Value of I "+i);
                          Thread.sleep(500);
                         }
        }
    });
myThread.start();

or if there is more complex operations you make you will have to use AsyncTask calss



来源:https://stackoverflow.com/questions/20292760/display-values-dynamically-in-textview-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!