James Rattray James Rattray - 9 months ago 40
Android Question

How to align view to right of another without squashing

Surely this is a frequent usecase but I can't seem to resolve it with a LinearLayout (or RelativeLayout) but maybe i'm missing something.

Best explained with an image:

enter image description here

I have a basic textview chatbubble with another textview aligned to the right (the timestamp for the message).

Both are

(but the timestamp could be set to like precisely 40dp but doesnt seem to matter).

Now in first (top) message it is short so you can see the view to the right.

But in the second the string is long so the
has taken up the whole width of the phone, pushing the timestamp textview out of the screen (horizontal linearlayout, but relativelative
does the same)

So how can I place a timestamp aligned right of another view, but the timestamp will be guarenteed size (not wrap/squash -the message bubble string wraps instead)

(I realise I could use a RTL layout, but I have messages from both sides so I would need LTR in other cases + min sdk api 17 is too high for a layout hack).

Any help would be greatly appreciated as I must have missed something obvious.

Answer Source

If you use a LinearLayout widget with horizontal orientation and one of its children wants to take all the available horizontal space then you should use layout weight.

For the first TextView set:


For the second TextView:


In this case you say that second TextView will take as much horizontal space as needed and the first TextView will take the rest. "0dp" is just an optimization to prevent extra layout measure calls.