Question

I'm having trouble building a layout. My situation is this:

I have an Activity that runs and has a layout defined for both normal and landscape, but they are built in runtime from onCreate().

In onCreate() I make the call to setContentView(my_normal_layout) which is then added to using a lot of addView()'s etc and works fine. However I am also trying to build my landscape layout but have the problem that when I try and use findViewById() to get my base layout which is part of my layout file stored in res/layout-land it returns null.

Now I've looked at solutions for people having the null return problem but people are suggesting that setContentView must be executed first. However I don't want to set the content view to be my landscape layout, I only want that to happen when the screen is rotated (it does this automatically?).

So does anyone know how I can get around this problem of using findViewById and altering my view that isn't set as the content view?

I can post any lines of code that are required but I'm hoping that explanation is good enough. Thanks,

Josh

Was it helpful?

Solution

If I understand correctly, you have different UI elements in the two different layout files.

If that is the case then you can still name the layout files the same (one in /res/layout and one in /res/layout-land) and use setContentView(...) to automatically inflate the correct one.

After that, all you need to know is what the current orientation is (portrait or landscape) in order to know which bits of code to call with findViewById(...).

You can find the orientation using...

getWindowManager().getDefaultDisplay().getOrientation();

If you are using API 8 (Android v2.2) or later, the above is deprecated however and you should call getRotation() instead of getOrientation().

See Display.getOrientation()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top