Is it possible to set in the XML layout file the size of the button so that, on one hand, it doesn't take the entire width of the parent (screen) and, on the other hand, doesn't use absolute pixel values?
To better explain my question, the problem in the following snippet is that "match_parent"
takes the entire width:
<Button android:id="@+id/btn_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="16px"
android:paddingLeft="16px"
android:paddingRight="16px"
android:paddingTop="16px"
android:text="@string/first_button" />
I know that it's possible to control the size during runtime but I am interested to know whether this is possible in an XML file as well.
Is there something like android:layout_width="match_HALF_parent"
?
Layout weights can do this. Basically what you need to do is to set a weightSum in the parent layout, and then set a layout_weight in the child:
<?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"
android:weightSum="2" android:orientation="horizontal">
<Button android:id="@+id/btn_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingBottom="16px"
android:paddingLeft="16px"
android:paddingRight="16px"
android:paddingTop="16px"
android:text="@string/first_button" />
</LinearLayout>
It is the relationship between the parent's weightSum and the child's weight which determines the width of the child: in this case it will be half; if we were to increase the parent's weight sum to 3, the child would be one third the width of its parent.
I have written about this on my blog.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With