在Android中,当我设置一个按钮的背景图片时,当我点击它时,我看不到任何效果。
我需要在按钮上设置一些效果,这样用户就可以识别出按钮被点击了。
单击该按钮时,该按钮应该会变暗几秒钟。该怎么做呢?
发布于 2011-08-24 21:13:31
这可以通过创建一个包含按钮状态列表的可绘制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),而不是块颜色。
发布于 2013-02-11 22:54:07
如果您有很多图像按钮,并且不想为每个按钮都编写xml-s,则会更简单。
Kotlin版本:
fun buttonEffect(button: View) {
button.setOnTouchListener { v, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> {
v.background.setColorFilter(-0x1f0b8adf, PorterDuff.Mode.SRC_ATOP)
v.invalidate()
}
MotionEvent.ACTION_UP -> {
v.background.clearColorFilter()
v.invalidate()
}
}
false
}
}Java版本:
public static void buttonEffect(View button){
button.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
v.getBackground().setColorFilter(0xe0f47521,PorterDuff.Mode.SRC_ATOP);
v.invalidate();
break;
}
case MotionEvent.ACTION_UP: {
v.getBackground().clearColorFilter();
v.invalidate();
break;
}
}
return false;
}
});
}发布于 2013-08-28 19:56:47
创建决定按钮淡入淡出效果程度的AlphaAnimation对象,然后让它从按钮的onClickListener开始
例如:
private AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.8F);
// some code
public void onClick(View v) {
v.startAnimation(buttonClick);
}当然,这只是一种方法,并不是最受欢迎的方法,它只是更简单
https://stackoverflow.com/questions/7175873
复制相似问题