如何在单击时更改按钮在Android中的颜色? [英] How to Change color of Button in Android when Clicked?
问题描述
我的工作在Android上的应用。我想有4个按钮被在屏幕的底部水平放置。在这4个按键2个按钮正在对它们的图像。按钮的边界应该是黑色的颜色和边界应该是尽可能地薄。当我按一下按钮,我希望按钮的背景应改为蓝色无边框的颜色被改变,并应保持在那个颜色一段时间。我怎样才能实现这个场景的Android?
I am working on Android Application. I want to have 4 buttons to be placed horizontally at the bottom of the screen. In these 4 buttons 2 buttons are having images on them. The border of the buttons should be black color and the border should be as thin as possible. When I click the button, I want the background of the button should be changed to blue color without the color of border to be changed and should be remained in that color for some time. How can I achieve this scenario in Android?
推荐答案
一种方法是在绘制
,被称为whatever.xml创建这样一个XML文件:
One approach is to create an XML file like this in drawable
, called whatever.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:state_pressed="true"
android:drawable="@drawable/bgalt" />
<item android:state_focused="false" android:state_pressed="true"
android:drawable="@drawable/bgalt" />
<item android:drawable="@drawable/bgnorm" />
</selector>
bgalt
和 bgnorm
的PNG图像的绘制。
bgalt
and bgnorm
are PNG images in drawable.
如果您在活动编程方式创建的按钮,你可以设置背景:
If you create the buttons programatically in your activity, you can set the background with:
final Button b = new Button (MyClass.this);
b.setBackgroundDrawable(getResources().getDrawable(R.drawable.whatever));
如果您设置按钮的风格与XML,你会做这样的事情:
If you set your buttons' style with an XML, you would do something like:
<Button
android:id="@+id/mybutton"
android:background="@drawable/watever" />
最后一个链接到一个教程。 希望这有助于。
And finally a link to a tutorial. Hope this helps.
这篇关于如何在单击时更改按钮在Android中的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!