如何使按钮居中并且其宽度是容器的百分比?

How to center a button and that its width is a percentage of the container?

我正在 Android Studio 中制作应用程序,我需要一个位于 phone 屏幕中央的按钮。

我看过很多关于如何让按钮居中的例子,但除此之外,一旦居中,按钮的宽度必须是屏幕宽度的60%。

欢迎任何想法、建议或示例。

谢谢

你应该试试 ConstraintLayout。它所做的是从左 (20%) 和右 (80%) 添加两个准则,并将按钮的左右约束设置为这些准则:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toStartOf="@+id/guideline2"
        app:layout_constraintStart_toStartOf="@+id/guideline" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.2" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.8" />

</android.support.constraint.ConstraintLayout>

@MishaAkopov 的回答很好,但我会提供一个使用线性布局的单独解决方案。

通过将布局的权重和设置为 10,将按钮的权重设置为 6,按钮将占布局宽度的 60%。此外,您需要将 LinearLayout 的重力设置为中心或 center_horizontal 以确保按钮居中。

<LinearLayout
          android:orientation="horizontal"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:gravity="center_horizontal"
          android:weightSum="10">

     <Button
         android:layout_width="0dp"
         android:layout_height="40dp"
         android:layout_weight="6"
         android:text="My Button"/>

</LinearLayout>