LinearLayout - Vertically not align
I got a problem with LinearLayout on Android. I have four buttons. Each button has a fixed size, but the text can vary in length.
My problem is that they are not align with the top of each. They seen to be align with the top of the text inside of each botton which change depending on the number of line there is inside the button (See picture).
Also, I want to keep using LinearLayout as I will eventually use code will add buttons based on data from a database.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent">
<Button android:text="Line1 Line2" android:textSize="30dp" android:layout_width="160dp" android:layout_height="120dp"></Button>
<Button android:text="Line1 Line2 Line3" android:textSize="30dp" android:layout_width="160dp" android:layout_height="120dp"></Button>
<Button android:text="Line1" android:textSize="30dp" android:layout_width="160dp" android:layout_height="120dp"></Button>
<Button android:text="Line1" android:textSize="30dp" android:layout_width="160dp" android:layout_height="120dp"></Butto开发者_运维百科n>
</LinearLayout>
</LinearLayout>
EDIT: ANSWER (Can't answer my own question):
Ok, I just found the answer by myself. You have to add android:baselineAligned="false" to LinearLayout or any other similar control that could show the same behavior.
You can also fix this in the UI designer using the button called "Toggle Baseline Alignment".
So the resulting code is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:baselineAligned="false" android:layout_width="match_parent" android:layout_height="match_parent">
<Button android:text="Line1 Line2" android:textSize="30dp" android:layout_width="160dp" android:layout_height="120dp"></Button>
<Button android:text="Line1 Line2 Line3" android:textSize="30dp" android:layout_width="160dp" android:layout_height="120dp"></Button>
<Button android:text="Line1" android:textSize="30dp" android:layout_width="160dp" android:layout_height="120dp"></Button>
<Button android:text="Line1" android:textSize="30dp" android:layout_width="160dp" android:layout_height="120dp"></Button>
</LinearLayout>
</LinearLayout>
its better to use RelativeLayout for such type of alignment, as RelativeLayout's concept says that it "reference" of a control
Well your second linear layout is whats creating the trouble I guess for u, just remove that
You can use TableLayout instead of Your Second LinearLayout.And add a TableRow inside the TableLayout and in the row add four buttons
精彩评论