1
votes

I have a view in my android app that I would like to toggle between visible/gone on smaller screens, and visible/invisible in larger sizes. The initial set up (gone for small, invisible for large screens) is done by having two separate XML layout files under layout and layout-sw600dp-land, but then when I need to dynamically swap the visibility setting, how can I determine from within Java code which one to pick based on screen size?

Edit: more specifically, I want to detect in my code the same condition that causes Android to use layouts from layout-sw600dp-land. I was thinking even recording the value somewhere in the values-sw600dp-land directory, but not sure which file to put it into and how to access it.

1
Just out of curiosity, why do you need to do this dynamically?mikołak
I need to toggle the visibility of a view based on the results of some calculations and input from the user. It works best when the "invisible" state is invisible in the large screen landscape layout, but gone in all others.SaltyNuts
I see. I was going to suggest using the tag attribute, but I see one of the answers in the question linked by ChrisCM already covers that.mikołak

1 Answers

4
votes

You can get the size in pixels of the screen using the following.

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels; 
int height = dm.heightPixels; 

However, your question was ambiguous as to whether size of screen meant pixels or inches. You may need to take advantage of the dm.densityDpi value, to convert the values from pixels to inches, for a more useful calculation of the "size" of the screen.

ANSER FOR EDITS:

There are two potential solutions. One is referenced in this thread, very simple and you alluded to it above.

How to programatically determine which XML layout my Android apps is using?

The second isn't a solution, but rather an explanation. The layout-sw600dp-land file replaces an old naming convention pre 3.2 that went like this layout-xlarge-land. This essentially manes "xlarge" screen in "landscape" mode. So you can detect this programmatically by finding xlarge screen sizes, in which the width > height. Below is a good reference to compare the old convention vs the new "sw600dp" = smallest width is 600 dp convention.

http://developer.android.com/training/multiscreen/screensizes.html