这是我第一次发帖。我一直使用这个网站作为一个很好的资源。 但我遇到了一个问题。我尝试对 ImageButton 应用阴影效果,但不起作用?我想要实现的是你可以在浮动气泡上看到的阴影(材质设计)。我有一个圆形 ImageButton,但我希望在它周围添加阴影。我怎样才能做到这一点?
这是circle_button.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#C62666"/>
</shape>
这是circle_button_pressed.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#E92D6C"/>
</shape>
这是我的选择器,它将两个可绘制对象合并为一个。按钮.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/circle_button"
android:state_focused="true"
android:state_pressed="true" />
<item android:drawable="@drawable/circle_button_pressed"
android:state_focused="false"
android:state_pressed="true" />
<item android:drawable="@drawable/circle_button_pressed"
android:state_focused="true" />
<item android:drawable="@drawable/circle_button"
android:state_focused="false"
android:state_pressed="false" />
</selector>
这就是我将其应用到我的 ImageButton 的方式
<ImageButton
android:id="@+id/btn_apply"
android:layout_width="68dp"
android:layout_height="68dp"
android:layout_alignParentTop="true"
android:layout_alignRight="@+id/scrollView1"
android:layout_marginRight="45dp"
android:layout_marginTop="94dp"
android:adjustViewBounds="true"
android:background="@drawable/button"
android:scaleType="fitCenter"
android:src="@drawable/apply_two" />
又这样?如何为按钮添加阴影?感谢您的宝贵时间。
您可以结合使用标高和带有阴影的可绘制背景。以下是修改 ImageButton 来实现此效果的方法: 首先,将 ImageButton 包裹在 CardView 内以利用海拔属性,该属性会自动添加阴影。
<androidx.cardview.widget.CardView
android:id="@+id/cardView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
app:cardCornerRadius="34dp" <!-- it should be half of your button's width or height -->
app:cardElevation="8dp">
<ImageButton
android:id="@+id/btn_apply"
android:layout_width="68dp"
android:layout_height="68dp"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:src="@drawable/apply_two"
android:background="@null" />
</androidx.cardview.widget.CardView>
其次,确保在 build.gradle 文件中添加 CardView 依赖项:
implementation 'androidx.cardview:cardview:1.0.0'
第三,调整layout_width、layout_height和app:cardCornerRadius值以适合您的设计。 app:cardCornerRadius 应该是按钮宽度或高度的一半才能创建圆形。
最后,从 ImageButton 中删除 android:background="@drawable/button" 属性,以允许 CardView 处理阴影。