gpt4 book ai didi

java - onLongClick 多类自定义按钮

转载 作者:行者123 更新时间:2023-12-01 15:14:52 32 4
gpt4 key购买 nike

这是我的代码

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.Button;

public class MyLongPressCustomButton extends Button{

private InStock instock;

public MyLongPressCustomButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}

public MyLongPressCustomButton(Context context, AttributeSet attrs) {
super(context, attrs);
}

public MyLongPressCustomButton(Context context) {
super(context);
}

public void setSampleLongpress(InStock sl) {
instock = sl;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
cancelLongpressIfRequired(event);
return super.onTouchEvent(event);
}

@Override
public boolean onTrackballEvent(MotionEvent event) {
cancelLongpressIfRequired(event);
return super.onTrackballEvent(event);
}

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
|| (keyCode == KeyEvent.KEYCODE_ENTER)) {
cancelLongpress();
}
return super.onKeyUp(keyCode, event);
}

private void cancelLongpressIfRequired(MotionEvent event) {
if ((event.getAction() == MotionEvent.ACTION_CANCEL)
|| (event.getAction() == MotionEvent.ACTION_UP)) {
cancelLongpress();
}
}

private void cancelLongpress() {
if (instock != null) {
instock.cancelLongPress();
}
}
}

我需要用于多类,现在仅适用于 InStock 类,如何更改我的多类代码?当我将 InStock 更改为 Activity 时,cancelLongpress() 方法未定义。

提前致谢:)

最佳答案

您应该使用delegate pattern在这种情况下。

  public interface MyDelegate{
void cancelLongPress();
}

然后将此委托(delegate)用于您的自定义按钮

 public class MyLongPressCustomButton extends Button{
MyDelegate delegate;

public MyLongPressCustomButton (MyDelegate delegate){
this.delegate = delegate;
}

private void cancelLongpress() {
if (null != delegate) {
delegate.cancelLongPress();
}
}
}

如果您想在许多类中使用它,只需实现该接口(interface)即可。例如

  public class YourActivity extend Activity implements MyDelegate{
@override
void oncreate(){
//create new button with a delegate
MyLongPressCustomButton btn = new MyLongPressCustomButton(this);
//do something
}

//real work is here
@override
public void cancelLongPress(){

}
}

关于java - onLongClick 多类自定义按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11770834/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com