如何为按钮添加边框?在不使用图像的情况下,有可能做到这一点吗?


当前回答

在Material组件库中,只需使用带有Widget.MaterialComponents.Button.OutlinedButton样式的MaterialButton。

你可以使用strokeColor和strokeWidth属性自定义颜色和宽度

<com.google.android.material.button.MaterialButton
   ....
   style="?attr/materialButtonOutlinedStyle"
   app:strokeColor="@color/colorPrimary"/>


使用Jetpack组合使用outline button。 使用border属性自定义宽度和颜色。

OutlinedButton(
    onClick = { },
    border = BorderStroke(1.dp, Color.Blue),
) {
    Text(text = "BORDER")
}

其他回答

在你的可绘制文件夹中创建一个名为gradient_btn的可绘制文件 并粘贴下面的代码

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient android:startColor="#7BF8C6"
    android:centerColor="#9DECAD"
    android:endColor="#7BF8C6"
    android:angle="270" />
<corners
    android:topLeftRadius="15dp"
    android:topRightRadius="15dp"
    android:bottomLeftRadius="15dp"
    android:bottomRightRadius="15dp"
    />
<stroke android:width="3px" android:color="#000000" />

</shape>

然后在你的xml按钮代码调用你创建的文件:

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:background="@drawable/gradient_btn"/>

输出-将是一个带有渐变和边框的按钮。

注意-你可以改变按钮的十六进制代码,如你所愿,也可以改变笔画宽度。

我知道这晚了一年,但你也可以创建一个9路径图像 android SDK中有一个工具可以帮助创建这样的图像 请看这个链接:http://developer.android.com/tools/help/draw9patch.html

PS:图像也可以无限缩放

请看这里关于创建一个可绘制的形状 http://developer.android.com/guide/topics/resources/drawable-resource.html#Shape

一旦你这样做了,在XML中为你的按钮集android:background="@drawable/your_button_border"

如果你的按钮不需要透明的背景,那么你可以使用框架布局创建一个边框的错觉。只需调整FrameLayout的“padding”属性来改变边框的厚度。

<FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="1sp"
        android:background="#000000">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Your text goes here"
            android:background="@color/white"
            android:textColor="@color/black"
            android:padding="10sp"
            />
</FrameLayout>

我不确定形状xml文件是否具有动态可编辑的边界颜色。但是我知道有了这个解决方案,你可以通过设置FrameLayout背景动态地改变边框的颜色。

<com.google.android.material.button.MaterialButton
                android:id="@+id/addBtn"
                style="@style/Widget.MaterialComponents.Button.OutlinedButton"
                android:layout_width="150dp"
                android:layout_height="80dp"
                android:gravity="center"
                android:backgroundTint="@android:color/transparent"
                android:textColor="@color/blue"
                app:cornerRadius="8dp"
                app:strokeColor="@color/blue"
                app:strokeWidth="2dp"/>