如何在Android中设置按钮点击效果?

新手上路,请多包涵

在Android中,当我为按钮设置背景图像时,单击它时看不到任何效果。

我需要在按钮上设置一些效果,这样用户才能识别出按钮被点击了。

单击该按钮时,它应该会变暗几秒钟。这个怎么做?

原文由 Jignesh Ansodariya 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 643
2 个回答

这可以通过创建一个包含按钮状态列表的可绘制 xml 文件来实现。例如,如果您使用以下代码创建一个名为“button.xml”的新 xml 文件:

 <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/YOURIMAGE" />
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/gradient" />
    <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/gradient" />
    <item android:drawable="@drawable/YOURIMAGE" />
</selector>

要使背景图像在印刷时保持深色外观,请创建第二个 xml 文件并使用以下代码将其命名为 gradient.xml:

 <?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <bitmap android:src="@drawable/YOURIMAGE"/>
    </item>
    <item>
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <gradient android:angle="90" android:startColor="#880f0f10" android:centerColor="#880d0d0f" android:endColor="#885d5d5e"/>
        </shape>
    </item>
</layer-list>

在按钮的 xml 中,将背景设置为按钮 xml,例如

android:background="@drawable/button"

更改了上面的代码以在按钮中显示图像(YOURIMAGE)而不是块颜色。

原文由 Ljdawson 发布,翻译遵循 CC BY-SA 4.0 许可协议

设置查看点击效果的简单方法。

方法

public AlphaAnimation clickAnimation() {
    return new AlphaAnimation(1F, 0.4F); // Change "0.4F" as per your recruitment.
}

在视图中设置

yourView.startAnimation(clickAnimation());

原文由 Kumar Santanu 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题