我有简单的自定义按钮:
public class myButton extends Button {
public myButton (Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
commonConstructorCode();
}
public myButton (Context context, AttributeSet attrs) {
super(context, attrs);
commonConstructorCode();
}
public myButton (Context context) {
super(context);
commonConstructorCode();
}
private void commonConstructorCode() {
this.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
if(action == MotionEvent.ACTION_DOWN)
{
//Just to be sure that we removed all callbacks,
// which should have occurred in the ACTION_UP
removeCallbacks(repeatClickWhileButtonHeldRunnable);
//Perform the default click action.
performClick();
//if(v.isEnabled()){
//Schedule the start of repetitions after a one half second delay.
postDelayed(repeatClickWhileButtonHeldRunnable, initialRepeatDelay);
//} else {
// removeCallbacks(repeatClickWhileButtonHeldRunnable);
//}
}
else if(action == MotionEvent.ACTION_UP) {
//Cancel any repetition in progress.
removeCallbacks(repeatClickWhileButtonHeldRunnable);
}
//Returning true here prevents performClick() from getting called
// in the usual manner, which would be redundant, given that we are
// already calling it above.
return true;
}
});
}
}
带选择器
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/button_pressed" /> <!-- pressed -->
<item android:state_focused="true"
android:drawable="@android:color/white" /> <!-- focused -->
<item android:drawable="@drawable/button_standard" /> <!-- default -->
</selector>
由
设置<com.blabla.myButton
...
background="@drawable/button_selector" />
处于“正常”状态的背景很好。但其他州根本不起作用。有什么奇怪的 - 当我改变时
<com.blabla.myButton
到
<Button
选择器工作得很好。
有什么想法吗?
修改 我添加了commonConstructorCode()。
答案 0 :(得分:1)
您可以尝试在自定义xml视图上设置此项。
android:focusable = "true"
我有一个类似的问题,并将焦点设置为true允许视图读取正确的状态并应用选择器。
答案 1 :(得分:1)
我复制了你的代码并使自定义按钮选择器工作但设置:
@Override
public boolean onTouch(View v, MotionEvent event) {
// Blah blah blah....
return false; // this was return true
}
});
根据android文档,公共布尔值onTouch(),
返回:如果侦听器已使用该事件,则返回true,否则返回false。
因此,返回true表示您的方法已经消耗了该事件,并且似乎停止它会逐步修改层次结构并触发选择器状态。
答案 2 :(得分:0)
在您的类的构造函数中,使用以下代码:
this.setBackgroundResource(drawable.button_selector);
我试试看。完美运作