Goo*_*ofy 0 android effects colorfilter android-button android-drawable
我有两个不同父母的按钮.
我正在尝试将按钮效果应用于按钮触摸.
这是我的代码:
public class ButtonHighlighterOnTouchListener implements OnTouchListener {
final Button button;
public ButtonHighlighterOnTouchListener(final Button imageButton) {
super();
this.button = imageButton;
}
public boolean onTouch(final View view, final MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
button.getBackground().setColorFilter(Color.parseColor("#B7B2B0"), PorterDuff.Mode.MULTIPLY);
button.invalidate();
break;
case MotionEvent.ACTION_CANCEL:
button.getBackground().clearColorFilter();
button.invalidate();
break;
case MotionEvent.ACTION_UP:
button.getBackground().clearColorFilter();
button.invalidate();
break;
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
它将效果应用于按钮,但问题是因为我有2个按钮,即使我点击一个按钮,效果也会应用到另一个按钮.
请帮我解决这个问题.
view在onTouch你的情况下,方法是Button被点击.而不是
button.getBackground().setColorFilter(Color.parseColor("#B7B2B0"), PorterDuff.Mode.MULTIPLY);
Run Code Online (Sandbox Code Playgroud)
使用
view.getBackground().setColorFilter(Color.parseColor("#B7B2B0"), PorterDuff.Mode.MULTIPLY);
Run Code Online (Sandbox Code Playgroud)
在其他情况下切换也一样.
编辑
相反,使用样式:
//background_button.xml in drawable folder
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" >
//Here you can set style you want when Button is pressed
<shape>
<solid
android:color="#22228C" />
<stroke
android:width="1dp"
android:color="#9999DE" />
<corners
android:radius="7dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
<item>
//Here you can set style you want when button is not pressed
<shape>
<gradient
android:startColor="#5858C8"
android:endColor="#22228C"
android:angle="90" />
<stroke
android:width="1dp"
android:color="#9999DE" />
<corners
android:radius="7dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
</selector>
//In your xml
<Button
android:background="@drawable/background_button" ... />
Run Code Online (Sandbox Code Playgroud)
编辑2
Button有一个构造函数,您可以在其中告诉您要应用哪种样式.
public Button (Context context, AttributeSet attrs, int defStyle);
Run Code Online (Sandbox Code Playgroud)
所以你可以设置defStyle = android.R.style.Button和styles.xml添加
<style name="Button">
<item name="android:background">@drawable/background_button</item>
</style>
Run Code Online (Sandbox Code Playgroud)
有了这个,我想你可以用你Button的风格初始化你的风格(你将突出显示效果background_button.xml)并添加你现在拥有的背景图像.