Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android setting Button width half the screen

How to setup(in XML) that the button will have width half of screen. I found only wrap content, match parent(fills whole screen) and exact amount of dp eg: 50dp. How to set it exactly hold the screen?

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
 android:weightSum="2"
>

 <Button
     android:id="@+id/buttonCollect"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_weight="1"
     android:paddingLeft="8dp"
     android:paddingRight="8dp"
     android:text="przycisk" />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:text="Button" />

like image 483
Yoda Avatar asked Nov 30 '22 02:11

Yoda


2 Answers

This is not possible in XML. However, you can do it in Java by getting the width of the display using DisplayMetrics, dividing it by 2 and setting it as the width of the button. Something like this:

Button button = (Button) findViewById(R.id.button);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = displaymetrics.widthPixels;
int buttonWidth = width/2;
//Apply this to your button using the LayoutParams for whichever layout you have.
like image 36
Raghav Sood Avatar answered Dec 01 '22 14:12

Raghav Sood


This can be done by having two widgets on your layout: use a LinearLayout and set layout_width="fill_parent" on both widgets (Button and another widget ), and set layout_weight also to the same value . and the LinearLayout will split the width between the two widget equally and your button will occupy half of the screen.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:orientation="horizontal">

 <Button
     android:id="@+id/buttonCollect"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:layout_weight="1"
     android:paddingLeft="8dp"
     android:paddingRight="8dp"
     android:text="przycisk" />

<Button
    android:id="@+id/button2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:text="Button" />
like image 164
Mouna Cheikhna Avatar answered Dec 01 '22 15:12

Mouna Cheikhna