Home > Back-end >  Kotlin TextView width - Only the original thread that created a view hierarchy can touch its views
Kotlin TextView width - Only the original thread that created a view hierarchy can touch its views

Time:11-20

I want to set text of a TextView in a thread but I want the TextView to be only wide enough just to fit a Text. I have:

<TextView
    android:id="@ id/txtTime"
    style="@style/txtItem"/>

Style:

<style name="txtItem">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
</style>

Thread:

private val thread = Thread {
    txtTime.text = timers.totalTime
}

When TextView is empty the wrap_content property makes it 0 width - it's not visible in design editor. When I run app I get:

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

The app runs fine only when the TextView width is enough to fit the string that I want to set, so it is working when I add to the style for example:

android:layout_width="100dp"

Interestingly the app crashes with the same exception if I use min_width instead of layout_width

android:minWidth="100dp"

I'd like to have the narrowest TextView that is wide enough just to fit a Text. How to do that?

CodePudding user response:

You cannot change any property of a view on a separate thread. It must be done on the main thread. There are cases where this is not caught at runtime and you can get away with it, but you are doing something considered unsafe. If you need to calculate/fetch something on a background thread, then you can callback to the main thread using post. For example:

private val thread = Thread { 

    // Do something in background

    txtTime.post { txtTime.text = timers.totalTime }
}

Regarding your other problem, I think you have a misconception about wrap_content. The size of your TextView will change to fit the text every time you set new text on the view, so it doesn't matter if it starts with 0 width and you add text to it later. And if you want to see what it looks like in the editor, you can use tools:text:

<TextView
    android:id="@ id/txtTime"
    style="@style/txtItem"
    tools:text="Some sample text"/>
  • Related