Reputation: 12424
I got a vertical LinearLayout, in which there's a button. I want to make this button 70% of the width of the LinearLayout and center it.
I've tried setting layout_weight
to 0.7 while setting the layout_width
to 0, but since it's a vertical LinearLayout, it doesn't affect the width, but can only affect the height.
How can I change the weight of the width in a vertical layout? Will I must add a nesting horizontal LinearLayout just for the button so I can set its weight?
Upvotes: 0
Views: 2958
Reputation: 935
Try using new PercentRelativeLayout, and you can achieve what you are trying without nested layouts.
include this in your dependencies :com.android.support:percent:25.1.0
And then in your code
<android.support.percent.PercentRelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
...
<Button
app:layout_widthPercent="70%"
android:layout_height="wrap_content"/>
...
</android.support.percent.PercentRelativeLayout>
Upvotes: 2
Reputation: 1426
Try this:
<LinearLayout>
<Space android:layout_weight=0.15/>
<Button android:layout_weight=0.7/>
<Space android:layout_weight=0.15/>
</LinearLayout>
https://developer.android.com/reference/android/widget/Space.html
I also suggest you put the values in dimens.xml
file.
Upvotes: 0
Reputation: 951
Please check this out.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.7"
android:gravity="center"
android:orientation="vertical">
<Button
android:id="@+id/yourRequiredButton"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<Button
android:id="@+id/container"
android:layout_weight="0.3"
android:layout_width="match_parent"
android:layout_height="0dp" />
</LinearLayout>
Upvotes: 0
Reputation: 9150
linearLayout -> orientation = horizontal
button -> layout width = 0dp
-> layout height = wrap_content
-> layout weight = 1
Upvotes: 0