如何为自定义按钮设置点击监听器?

How to set on click listener for a custom button?

我尝试为我的自定义按钮设置监听器 class。但是,我的听众似乎没有映射到视图。想结合我的按钮视图和自定义按钮吗?

我的片段在线性布局上带有自定义按钮 XML

<LinearLayout>
 ...
<Button>
...
</Button>

<LinearLayout>

我尝试在 onActivityCreated 方法中为片段中的按钮设置点击侦听器。

public class myFragment extend Fragment {

@Override
public void onActivityCreated (){

Button myNewButton = new myButton();
myNewButton = root.findViewByID.(R.id.button);
myNewButton.setOnClickListener(new myButton());

}

}

我的自定义按钮 class 使用 setonclicklistener 方法

public class myButton extend button implements View.onClicklistener {

@Override
public void setOnClickListener (OnClickListener listener){
super.setonClickListener(listener);
}

@Override
public void onClick(View view) {
//action to do after on click
}

}

试试这个:

myFragment 中删除此行:

myNewButton.setOnClickListener(new myButton());

myButton 中执行此操作:

public class myButton extend button implements View.onClicklistener {

@Override
public void setOnClickListener (OnClickListener listener){
//set like this
super.setonClickListener(this);
}

@Override
public void onClick(View view) {
//action to do after on click
}

}

您似乎将另一个按钮设置为原始按钮的侦听器,这取决于您希望在侦听器中执行的操作,这可能会产生意外行为。

更简单的解决方案是将自己设置为监听器,虽然您已经在 MyButton 中实现了 View.onClicklistener,但您还没有将其设置为自己的监听器。您需要在构造函数中这样做。

如果您希望支持用户设置 onClickListeners 以及 MyButton 侦听器,那么您需要在 MyButton class 中维护一个侦听器变量,然后您可以明确地打电话。

最后,直接在您的布局中使用您的 MyButton,而不是像您目前似乎正在做的那样使用 Button

你的最终 MyButton class 应该是以下几行,

public class MyButton extends androidx.appcompat.widget.AppCompatButton implements View.OnClickListener {

    public MyButton(Context context) {
        super(context);
        init();
    }

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

    public MyButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setOnClickListener(this);
    }

    private View.OnClickListener mUserOnClickListener;

    @Override
    public void setOnClickListener(@Nullable OnClickListener l) {
        if (l == this) {
            super.setOnClickListener(l);
        } else {
            mUserOnClickListener = l;
        }
    }

    @Override
    public void onClick(View v) {
        //Your actions
        Toast.makeText(getContext(), "MyButton clicked", Toast.LENGTH_SHORT).show();
        if (mUserOnClickListener != null) {
            mUserOnClickListener.onClick(v);
        }
    }
}

P.S - 我还建议您仔细阅读 Java.

的命名约定