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.
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);