Friday 7 October 2011

Android Annoyances: Layout Rules

Quite often, working with Android, I have a strong feeling that a method is missing that actually should exist in the API. Say, there can be a getter but no setter. In some cases, I understand that the property I am trying to change is read-only, but in the other cases there is an impression that someone who was designing the API just didn’t spend enough time thinking on it.

Here is one of the recent stories.

Android doesn’t give us many opportunities for controlling the positioning of views and controls. This is understandable: taking into account the wide array of screen sizes and densities, we’d better trust the automatic layout and pray that it does something good for us. However, we can still achieve quite a lot by manipulating layout parameters, and RelativeLayout is probably the most helpful in this respect.

RelativeLayout.LayoutParams method offers us a couple of useful methods:

addRule(int verb)
addRule(int verb, int anchor)

Using them, we can dynamically, in the code, put a view on top of another view, or align it, say, to parent bottom.

Great, so we can add a rule that we need. Surely, there should be a possibility to remove the rule that we don’t need anymore, right? Say, we’ve aligned a view to parent bottom first, but then we want to place it above another view. We might try to do it like this:

params.addRule(RelativeLayout.ABOVE, R.id.someview);

But this won’t work: the view will stay aligned to the parent bottom. There should be a method to remove a rule that was added - but go try to find it in the API. It doesn’t exist.

Quite typically, Android still leaves us a possibility to achieve what we want but at the price of writing some ugly code - and spending time to discover that ugly solution. Here is how I managed to remove the rule that I don’t need anymore:

params.getRules()[RelativeLayout.ALIGN_PARENT_BOTTOM] = 0;

If you know a better way, please let me know.

No comments:

Post a Comment