是否可以在XML中设置事件监听器? [英] Is it possible to set event listener in XML?

查看:182
本文介绍了是否可以在XML中设置事件监听器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用XML设计布局时,我在Java代码中使用findViewById()来加载视图并为其设置侦听器.

When I using XML to design layout, I am using findViewById() in java code to load views and set listeners to them.

这是正确的吗?可能可以用XML或其他方式设置侦听器吗?

Is this correct what I am doing? May be it is possible to set listeners in XML or something?

推荐答案

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

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.

这篇关于是否可以在XML中设置事件监听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆