【问题标题】:Android: add pressed effect on a button with image, text under it and custom borderAndroid:在带有图像,文本和自定义边框的按钮上添加按下效果
【发布时间】:2018-11-22 20:46:12
【问题描述】:

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

main menu buttons

为了实现带有圆角的按钮布局,我将一个名为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" />

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

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

对于压制效果,我主要遵循@Ljdawson 对此主题的回答:click effect on button in Android 但没有成功,正如我上面解释的那样

我该怎么做?

【问题讨论】:

    标签: android xml image button text


    【解决方案1】:

    您的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_pressedbutton_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>
    

    【讨论】:

    • 工作就像一个魅力!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    • 1970-01-01
    • 2012-09-03
    • 2011-10-11
    相关资源
    最近更新 更多