Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - How to set visibility in xml depending on device?

I have a TextView in my activity that should be visible normally, but gone for tablet devices.

I know I can create a new layout file for the tablet, but that seems like a lot of duplication, so what I am trying to do is set in my (single) layout file something like...

android:visibility="@string/my_textview_visibility"

...for the TextView. And then, in my strings resources files, set...

<string name="my_textview_visibility">gone</string> (in values/strings.xml)

...and...

<string name="my_textview_visibility">visible</string> (in values-sw720dp/strings.xml)

...to hide the TextView for tablets.

However, when I try this, the app crashes when trying to show that activity.

Do I need to use the constant values instead of the above string values - e.g.,

"visible" -> 0

"gone" -> 8

..and, if so, what is the correct way to add/reference those values to/from my XML files?

Or is there another/better way of doing it?

NB - I do not want to show/hide the TextView programatically in my Java code.

like image 277
ban-geoengineering Avatar asked Mar 31 '17 15:03

ban-geoengineering


Video Answer


2 Answers

You should be using /values/integers/ instead:

values/integers.xml

<integer name="my_textview_visibility">0</integer> <!-- 0 = View.VISIBLE -->

values-sw720dp/integers.xml

<integer name="my_textview_visibility">2</integer> <!-- 2 = View.GONE -->

Then called like so:

android:visibility="@integer/my_textview_visibility"
like image 179
Chris Stillwell Avatar answered Nov 03 '22 01:11

Chris Stillwell


ChrisStillwell's answer is correct. But the values are incorrect according to the Android Documentation

enter image description here

like image 23
Robert Estivill Avatar answered Nov 02 '22 23:11

Robert Estivill