如何在android中制作一个胶囊形状按钮?

use*_*926 28 android button android-button

我想制作一个与此图像完全相同的按钮

胶囊按钮

我想使用一个用于生成这种按钮的xml文件.谁能告诉我怎么做?

use*_*926 53

最后我找到了用xml文件做的方法.这是给我胶囊形状按钮的xml文件的代码.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >

  <corners
    android:bottomLeftRadius="30dp"
    android:bottomRightRadius="30dp"
    android:radius="60dp"
    android:topLeftRadius="30dp"
    android:topRightRadius="30dp" />

  <solid android:color="#CFCFCF" />

  <padding
    android:bottom="0dp"
    android:left="0dp"
    android:right="0dp"
    android:top="0dp" />

  <size
    android:height="60dp"
    android:width="270dp" />

</shape>    
Run Code Online (Sandbox Code Playgroud)


Gab*_*tti 11

只需使用MaterialButtonusingapp:cornerRadius属性和您喜欢的宽度。

 <com.google.android.material.button.MaterialButton
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            app:cornerRadius="18dp"
            android:text="BUTTON"
            />
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

  • 这应该是使用 Material Components 进行现代 Android 开发的新公认答案 (3认同)

Hen*_*aWD 7

我没有在这里尝试所有答案,但我相信其中一些/全部是可行的。接受的答案也可以,但是可以简化。因为我喜欢优雅简单的解决方案,所以我提出了自己的解决方案。基本上,我们只需要添加与您的View宽度和高度相比足够大的半径,这样就可以创建一个圆角。在这种情况下,我1000dp要确保安全。我们甚至根本不需要添加android:shape="rectangle"

只需遵循以下两个简单步骤:

  1. 在您的可绘制文件夹中创建一个XML文件。例如,让我们命名bg.xml

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android">
        <corners android:radius="1000dp"/>
    
        <solid android:color="@color/yourPreferredColor"/>
    </shape>
    
    Run Code Online (Sandbox Code Playgroud)
  2. 然后,您可以在布局XML文件中将其用作View属性android:background="@drawable/bg" 或直接在代码中使用view.setBackgroundResource(R.drawable.bg)