Android设置按钮宽度为屏幕的一半

Yod*_*oda 4 xml layout android

如何设置(在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" />
Run Code Online (Sandbox Code Playgroud)

Mou*_*hna 14

这可以通过在布局上放置两个小部件来完成:使用LinearLayout并layout_width="fill_parent"在两个小部件上设置(按钮和另一个小部件),并将layout_weight也设置为相同的值.并且LinearLayout将平均分割两个小部件之间的宽度,您的按钮将占据屏幕的一半.

<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" />
Run Code Online (Sandbox Code Playgroud)


Rag*_*ood 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.
Run Code Online (Sandbox Code Playgroud)