带阴影的圆形按钮

时间:2015-02-05 18:37:50

标签: android android-layout

我创建一个带状态的圆形按钮,我想在按钮上添加阴影,就像默认按钮一样,我怎么做?这是我的代码:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true">

        <shape android:shape="oval">
            <solid android:color="@color/yellow_pressed" />
            <stroke android:width="1dp" android:color="#fff" />
        </shape>
    </item>

    <item android:state_focused="true">
        <shape android:shape="oval">
            <solid android:color="@color/yellow_pressed" />
            <stroke android:width="1dp" android:color="#fff" />
        </shape>
    </item>


    <item>
        <shape android:shape="oval">
            <solid android:color="@color/yellow_default" />
            <stroke android:width="1dp" android:color="#fff" />
        </shape>
    </item>

</selector>

1 个答案:

答案 0 :(得分:3)

从Lollipop开始,您可以使用:

public static void setOvalElevationToView(final View view) {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP)
        view.setOutlineProvider(new ViewOutlineProvider() {
            @TargetApi(VERSION_CODES.LOLLIPOP)
            @Override
            public void getOutline(View view, Outline outline) {
                final int size = view.getWidth();
                outline.setOval(0, 0, size, size);
            }
        });
}

您可能还需要在视图的父级上禁用剪裁,以便不会剪切阴影