Force the use of landscape resources for a custom VIEW with device in portrait orientation

Viewed 143

I am building a library of reusable components. These components are all custom Views (not Fragment or Activity). I have different layout files for each of these components to work best in portrait (view height > view width) and landscape (view width > view height). This works great when one of the components takes up the whole screen.

However, sometimes I will build an app that has several of these components on screen at the same time, for example:

multiple components

In this case, even thought the device is in landscape orientation, since the custom Views are each taller than they are wide, they should be using the portrait resources (layouts, dimensions, etc.).

I have a similar situation in portrait orientation:

multiple components port

Here it is clear that each View is wider than it is tall, so the View should be using the landscape resources instead of the portrait ones.

Even though this is basically a simple example of "responsive design", I have not found any easy/reasonable way to deal with this issue and am looking for clever solutions. Things to note before you write an answer/comment:

  • These components are Views, they must remain Views. The are not Fragment or Activity.
  • I do not intend to change the size of the View once it is placed on-screen. The View does not need true "responsive design" capabilities (ie: it must not resize dynamically or anything like that).
  • I have read this discussion about using window size classes and it does not help me because that is only relevant to the window hosting the App itself. In my case, I need a solution per View.
  • I do not want to force the device into either portrait or landscape mode. The user can switch between portrait and landscape mode and each View will be recreated, but it must use the appropriate resources based on the size of the View.

Any brilliant ideas?

1 Answers

There is no easy out-of-the-box way to achieve what you want with only the Android system API or supporting methods. I've looked for it a lot, and there are hacky ways I wouldn't recommend. I will give the only clean solution I found.

I've worked with similar views, and the general approach should be like this - create a custom view parameter that users of your library can use either in XML or directly in the code(or custom modifier if you intend to support composable) called orientation(aspectRatio/axis/etc.) with default to either landscape or portrait and based on that let your view to use relevant resources.

And move those resources from the landscape folder - for the android system not to misuse them - let your library users decide and control the UI for themselves.

Related