How to make button to fill 50% from the screen width in android?

Android

Android Problem Overview


I want to make the button to fill always 50% from the width of the screen, as when I rotate the device horizontally or vertically always the button fill 50% from the width.

Android Solutions


Solution 1 - Android

This should be possible by using weightSum and layout_weight:

<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_height="wrap_content"
 android:layout_width="fill_parent"
 android:orientation="horizontal"
 android:weightSum="1.0">
 <Button
  android:id="@+id/textbox3"
  android:layout_height="wrap_content"
  android:layout_weight=".5"
  android:layout_width="0dip"
  android:textSize="12sp" />
</LinearLayout>

Solution 2 - Android

To do this in code.

// Get screen width.
DisplayMetrics metrics = new DisplayMetrics();
WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);
final float width = metrics.widthPixels;
LinearLayout.LayoutParams layoutParamsWidth50 = new LinearLayout.LayoutParams(
    (int) (width/2) , ViewGroup.LayoutParams.MATCH_PARENT );
textbox3.setLayoutParams(layoutParamsWidth50);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdhamView Question on Stackoverflow
Solution 1 - AndroidRoflcoptrExceptionView Answer on Stackoverflow
Solution 2 - AndroidRuanView Answer on Stackoverflow