且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以在XML中设置事件监听器?

更新时间:2023-11-25 15:37:22

大多数人在代码中设置监听器.在代码中有时这样做更容易,因为您经常需要根据某些操作或状态添加或删除侦听器.

Most people set their listeners in code. It's sometimes easier to do it in code because you often times will need to add or remove listeners based on some action or state.

但是,Android还为您提供了为XML中的任何View设置OnClickListener的选项.这是一个示例:

However, Android also gives you the option of setting a OnClickListener for any View in XML. Here's an example:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="onActionClick"
    android:text="Action" />

使用onClick属性,为将处理单击的方法分配名称.此方法必须与View存在于同一Context中,因此必须存在于同一Activity中.因此,例如,我将必须实现此方法:

Using the onClick attribute, you assign the name of the method that will handle the click. This method must exist in the same Context as the View, so in the same Activity. So for example, I would have to implement this method:

public void onActionClick(View v) {

    // Do stuff for my "Action" button...
}

我相信它必须有一个View参数,就像实现OnClickListener一样.我也相信它必须是公开的.

I believe it has to have a View parameter, just like implementing OnClickListener would. I also believe it must be public.

那么***"的方式是什么?这取决于你.两条路线都是可行的.值得注意的是,这仅对单击侦听器有用,而对其他类型的侦听器无用.

So as far as which way is "best"? That's up to you. Both routes are viable. It's worth noting though that this is only useful for click listeners and not other types of listeners.