有个按钮,需要在平时是不启用状态,但是又需要长按来设置按钮的参数。
如果setEnable(false) 的话,长按也不管用。
相当于需要重写下 按钮的事件监听,比较简单,只做个记录,以后可以拿来用
public class MyButton extends Button{
private static final String TAG = "MyButton";
private Context context;
MyDialogSetting myDialogSetting; //自定义弹出框 用来设置
public MyButton(Context context) {
super(context);
this.context = context;
super.setOnLongClickListener(onLongClickListener);
}
public MyButton(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
super.setOnLongClickListener(onLongClickListener);
}
public MyButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.context = context;
super.setOnLongClickListener(onLongClickListener);
}
/**
* 设置只响应长按时间 不响应单击事件
*/
public void setOnlyAnsLongClick(boolean onlyAnsLongClick){
if(onlyAnsLongClick){
this.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//单击事件不响应
Log.i(TAG,"单击事件不响应");
return;
}
});
this.setBackground(context.getResources().getDrawable(R.drawable.btn_bg_gray));
}else {
this.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
shortClickListenerInterface.onShortClick(v);
}
});
this.setBackground(context.getResources().getDrawable(R.drawable.btn_bg_blue));
}
}
ShortClickListenerInterface shortClickListenerInterface;
public void setShortClicklistener(ShortClickListenerInterface clickListenerInterface) {
this.shortClickListenerInterface = clickListenerInterface;
}
public interface ShortClickListenerInterface {
public void onShortClick(View v);
}
OnLongClickListener onLongClickListener = new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Log.i(TAG,"按钮长按事件");
Button b = (Button)v;
myDialogSetting = new MyDialogSetting(context,b.getText().toString());
myDialogSetting.setClicklistener(new MyDialogSetting.ClickListenerInterface() {
@Override
public void doConfirm() {
//保存信息
Log.i(TAG,"保存信息");
myDialogSetting.dismiss();
}
@Override
public void doCancel() {
myDialogSetting.dismiss();
}
});
// myDialogSetting.show(); //暂时先不用长按事件
return true;
}
};
}
使用该按钮的时候,不再使用系统默认监听,使用如下
btn1.setShortClicklistener(new MyButton.ShortClickListenerInterface() {
@Override
public void onShortClick(View v) {
//这个是短按监听
}
});
btn1.setOnlyAnsLongClick(false); //设置可监听短按和长按
btn1.setOnlyAnsLongClick(true); //设置只响应长按 不响应短按