James Andrew
James Andrew

Reputation: 7243

How to align view to right of another without squashing

Surely this is a frequent use-case 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 wrap_content (but the timestamp could be set to like precisely 40dp but doesn't 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 wrap_content has taken up the whole width of the phone, pushing the timestamp textview out of the screen (horizontal linearlayout, but relativelative toRightOf does the same)

So how can I place a timestamp aligned right of another view, but the timestamp will be guaranteed 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).

Upvotes: 2

Views: 284

Answers (2)

Leandro Borges Ferreira
Leandro Borges Ferreira

Reputation: 12792

Do this:

<LinearLayout
   android:width="match_parent"
   android:height="wrap_content"
   android:orientation="horizontal">

   <!-- the text -->
   <TextView
           android:width="0dp"
           android:height="wrap_content"
           android:weight="1"/>
<!-- the time -->
   <TextView
           android:width="match_parent"
           android:height="wrap_content"/>
</LinearLayout>

Or this:

 <LinearLayout
       android:width="match_parent"
       android:height="wrap_content"
       android:orientation="horizontal">

       <!-- the text -->
       <TextView
               android:width="match_parent"
               android:height="wrap_content"
               android:maxWidth="300dp"/> <!-- can be a different dimention -->
    <!-- the time -->
       <TextView
               android:width="match_parent"
               android:height="wrap_content"/>
    </LinearLayout>

Upvotes: 1

Gennadii Saprykin
Gennadii Saprykin

Reputation: 4573

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:

layout_width="0dp"
layout_weight="1"

For the second TextView:

layout_width="wrap_content"

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.

Upvotes: 1

Related Questions