简体   繁体   中英

Android TextView.setText working only sometimes inside Runnable

I have a postDelayed Runnable that counts down from 3 the executes some code x number of times. I am displaying text to the user via setText(). The setText() function works in some areas of an if,else if,else but does not work in other areas.

    final Runnable r1 = new Runnable() {
        @Override
        public void run() {
            if ((--count != 0) && (gestureCounter != selectedItems.size())) {
                mHandler.postDelayed(this, 1000);
                liveView.setText("Do " + selectedItems.get(gestureCounter) + " in " + String.valueOf(count));//works
            }
            else if(gestureCounter != selectedItems.size()){
                count=4;//3 seconds + 1
                liveView.setText("Hold " + selectedItems.get(gestureCounter));//NOT WORKING
                mHandler.post(this);
                fcalc.setTrain(true);
                while(fcalc.getTrain()){
                    //wait till trainig is done
                }
                gestureCounter++;
            }
            else{
                liveView.setText("");//works
                fcalc.Train();
                fcalc.setClassify(true);
            }
        }
    };
    mHandler.post(r1);

Please take a look at my comments to see which setText() functions work or don't. The one in the else if is the only one that is not working.

Any ideas?

Thank you for your help!

This is because of you are calling mHandler.post(this); this will call immediately the handler runnable again and also you are incrementing the value gestureCounter , so next time will come to this loop and it will go to first loop or 3rd loop as per condition

Try to add delay in that loop also and check

Edited:

Because of your while loop continuously running, UI is not updating, Just comment that and run the code like below condition it will work fine

like this

                    else if(gestureCounter != selectedItems.size()){
                    liveView.setText("Hold " +
                            selectedItems.get(gestureCounter));//NOT WORKING

                    mHandler.postDelayed(this, 1000); // delay added 

                    if(fcalc.getTrain()) {
                        return;
                    }
                    count=4;//3 seconds + 1

//                    fcalc.setTrain(true);
//                    while(fcalc.getTrain()){
//                        //wait till trainig is done
//                    }
                    gestureCounter++;
                }

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