首页 > 解决方案 > Android:在带有图像,文本和自定义边框的按钮上添加按下效果

问题描述

我正在做一个项目,我有一个主菜单,其中的按钮在图像下方有图像和文本,它们已经完成:

主菜单按钮

为了实现带有圆角的按钮布局,我将一个名为border_button的xml作为背景:

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="3dp" />
    <solid android:color="@color/colorPrimary" />
</shape>

为了使背景图像和文本保持圆角,我的按钮 xml 是这样的:

        <Button
            android:id="@+id/buttonMeusDados"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="2sp"
            android:layout_weight="1"

            android:background="@drawable/border_button"
            android:drawableTop="@drawable/button_image_icon_meus_dados"
            android:text="@string/my_data"
            android:textColor="@android:color/white" />

现在的问题是这些按钮在按下时不会向用户返回任何反馈,它们是静态的,没有按下动画

我找到了很多方法来做到这一点,但我无法将它们与我已经拥有的东西混合在一起,如果我制作按下效果动画,我会失去所有带有圆角等的矩形布局

对于按下的效果,我主要遵循这个主题的@Ljdawson 回答:click effect on button in Android but no success,正如我上面解释的那样

我该怎么做?

标签: androidxmlimagebuttontext

解决方案


border_button.xml应该是一个选择器。就像下面的例子:

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

    <!-- the order of items is important. The first one that matches the state is rendered. -->
    <item android:state_pressed="true" android:drawable="@drawable/button_pressed"/>
    <item android:drawable="@drawable/button_normal" />
</selector>

        <!-- to make transition more visible you can slow it down. 
             Add this inside of selector tag, after the xmlns:android="..."
             android:exitFadeDuration="@android:integer/config_longAnimTime"
          -->

button_pressed并且button_normal是绘制按钮的按下状态和正常状态的 xml 文件,示例如下:

<!-- button_pressed.xml -->
<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="3dp" />
    <solid android:color="@color/colorAccent" />
</shape>

<!-- button_normal.xml -->
<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="3dp" />
    <solid android:color="@color/colorPrimary" />
</shape>

推荐阅读