简体   繁体   中英

Android TextView not fully updating

I have a thread which updates a textview using a runnable:

// runnable to allow updating the UI from the thread
Runnable updateTextView = new Runnable() {

    public void run() {
        mTextView.setText(mDisplayedText);
        mTextView.invalidate();
    }
};

However, the text does not update properly. It works for the first few writes, then only writes half the text, leaving the second half of the previous text there.

Turning the screen around causes it to refresh and draws it correctly.

The textview is multiline and I write a string to it which contains \\n characters for the end of lines.

The invalidate call above makes no difference.

Any ideas?

UPDATE: mDisplayedText is declared in the activity which also contains my thread class. in the thread run loop, I call:

mDisplayedText = getText()
runOnUiThread(updateTextView);

The loop contains a 100ms sleep, but it only writes to the text when it has changed so in reality it will be less than once a second

ANSWER:

Slightly embarrassing this. The problem was in other code.

I was receiving a UDP socket into the same packet, and reading the packet.getData into a new string. This was copying the whole packet into the string, rather than just the bytes received in that message. The second problem was that I needed to call packet.setLength each time to set the length available to the whole packet.

Thanks for the answers!

you can only update your UI on UI thread, put your setText() method inside this

runOnUiThread(new Runnable() {
   @Override
   public void run() {
      btn.setText(someValue);
   }
});

Runnable is an interface. Think of it like a set of commands ready for execution. You can use a Handler to work with your code:

Handler textViewHandler = new Handler();

// runnable to allow updating the UI from the thread
Runnable updateTextView = new Runnable() {

    public void run() {
        mTextView.setText(mDisplayedText);
    }
};

textViewHandler.post(updateTextView);

Also, please consider @Karakuri's suggestion.

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