4

ボタンの幅が画面の半分になるように (XML で) 設定する方法。ラップコンテンツのみが見つかり、親(画面全体を埋める)と一致し、dpの正確な量(例:50dp)が見つかりました。画面を正確に保持する方法は?

<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" />

4

3 に答える 3

14

これは、レイアウトに 2 つのウィジェットを配置することで実行できます。LinearLayout を使用しlayout_width="fill_parent"て両方のウィジェット (Button と別のウィジェット) に設定し、layout_weight も同じ値に設定します。LinearLayout は 2 つのウィジェット間の幅を均等に分割し、ボタンは画面の半分を占めます。

<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" />
于 2012-07-01T22:40:15.960 に答える
8

これは XML では不可能です。ただし、 DisplayMetricsを使用してディスプレイの幅を取得し、それを 2 で割り、ボタンの幅として設定することで、Java でそれを行うことができます。このようなもの:

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.
于 2012-07-01T22:42:57.520 に答える