views:

78

answers:

2

I'm trying to get my textview to hug the left side of the screen while the button hugs the right side (and if possible just for ocd sake have the text view center itself vertically to be in line with the button) but not do it using absolute values. Here's my coding:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="100px"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:text="Change City:"
/>
<Button 
android:layout_width="100px" 
android:layout_height="wrap_content" 
android:layout_gravity="right"
android:text="Click" 
android:id="@+id/citychoicebutton"
/>
</LinearLayout>

I thought layout_gravity took care of what I'm trying to do but apparently not.

A: 

You could try using RelativeLayout with android:layout_alignParentLeft for TextView and android:layout_alignParentRight for Button. To align the button and TextView you could use android:layout_alignbaseLIne attribute on Button.

Megha Joshi
A: 

Gravity specifies how to place the element within the element itself, not within the boundaries of the parent (screen).

What this means is if your text takes only 50px in width but you have allocated 100px to TextView, the actual characters will place themselves to the left, center or right of the 100px space (as per gravity value).

With a LinearLayout, you will have to assume a screen width to reach your desired effect and use "dip" as a unit, and hope for the best (test it on different screen sizes on your emulator).

A better alternative is Relative Layout, and use android:layout_alignParentLeft and android:layout_alignParentRight.

Incidentally, it is recommended to use "dip" (density independent pixels) and not "px" for layout units in general.

FreewheelNat