Issue
I have been making an Android app. Android Studio rightly scolds me if I hardcode strings in the layout editor, so I put them in res/values/strings.xml
. For a simplified example:
<resources>
<string name="thing">Do a thing</string>
</resources>
I then set a button's text
property to @string/thing
. This correctly displays "Do a thing" in the layout editor, as expected. However, when I actually load my app on my phone with the default Run or Debug commands in Android Studio, the button is blank. This is interesting, as when I manually invoke resources.getString(R.string.thing)
, I do get "Do a thing"
back.
I can manually set the widgets' text fields this way, by doing acrobatics like:
findViewById<Button>(R.id.myButton).text = resources.getString(R.string.thing)
but this is a lot of work that as far as I know should be done automatically. This has happened to me in a Java app too, so the problem isn't Kotlin-specific. I'm using Android Studio 3.6 on Linux and the device is a Redmi Note 3 Pro with LineageOS 16 (Pie). The button is also blank when the app is launched in a virtual AVD, so clearly I must be doing something wrong. Here are the full activity layout and string XML files.
Solution
Each of your Button
widgets has tools:text
instead of android:text
:
<Button
android:id="@+id/nextButton"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
tools:text="@string/nav_next" />
android:text
is used for fixed text to be displayed at runtime and, by default, in the development tools.
tools:text
is for sample text to be displayed in development tools only. Mostly that is for cases where the text that you really want to use is not known until runtime (e.g., needs to be loaded from a database). Using tools:text
lets you get a sense of what the layout will really look like in the tools, while not pre-populating that text when your app runs.
So, switch from tools:text
to android:text
and you should get the results that you seek.
Answered By - CommonsWare
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.