简体   繁体   中英

Android TextView.setText() does nothing in button onClickListener

I am trying to change the text of a TextView after clicking a button. The text will display a countdown of seconds so the setText() function gets called several times inside a loop. The text never changes until after the entire onClickTrain function is finished.

I'm using fragments.

The Log.d(...) displays everything perfectly so I know the process is okay.

public  View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    final View v = inflater.inflate(R.layout.fragment_classification, container, false);
    assert v != null;

    liveView = (TextView)v.findViewById(R.id.textView3);

    View trainButton = v.findViewById(R.id.train);
    trainButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v){
            onClickTrain(v);
        }
    });

    return v;
}

public void onClickTrain(View v) {

    for(int i=0;i<numGestures;i++) {//countdown to train each gesture
        for (int countDown = 3; countDown > 0; countDown--) {//count down from 3

            Log.d("Hold ", ListElements[i] + " in " + String.valueOf(countDown));
            liveView.setText("Hold " + ListElements[i] + " in " + String.valueOf(countDown));

            SystemClock.sleep(1000);//wait 1 second
        }
        fcalc.setTrain(true);
        SystemClock.sleep(100);
        while(fcalc.getTrain()){
            //wait until training data is full
        }
    }
    Log.d("size of train vector: ", String.valueOf(fcalc.samplesClassifier.size()));
    fcalc.Train();
    fcalc.setClassify(true);

}

Any idea why the text is not displaying? I have tried using handlers in several different places.

Any input is appreciated. Thanks.

DO not sleep on the UI thread. This makes the app freeze. Redrawing requires the app to return control to the Looper in the event loop that calls your click handler. So if you sleep, your changes will not show.

You can use a handler to add a delay. If you use Thread.Sleep(5000) it will make the UI irresponsive.

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
      //Do something here
    }
}, 5000);

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