如何使按钮填充Android屏幕宽度的50%?


70

我想使按钮始终50%从屏幕的宽度填充,就像当我水平或垂直旋转设备时,按钮总是从屏幕50%的宽度填充。

Answers:


190

通过使用weightSum和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>

3

要用代码做到这一点。

// 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);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.