Is it possible to set event listener in XML?

2019-08-08 12:34发布

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

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

4条回答
来,给爷笑一个
2楼-- · 2019-08-08 13:16

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.

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" />

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...
}

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.

查看更多
三岁会撩人
3楼-- · 2019-08-08 13:16

You may specify android:onClick attribute when describe your View in XML. The value of this attribute is the name of the method which will be called at your View's onClick event. Then you should define this method as public in your code and you could pass there View object which will determine what View from those that you described at xml with the same android:onClick attributes has gotten touch event from user.

查看更多
我想做一个坏孩纸
4楼-- · 2019-08-08 13:26

There is an onClick attribute that you can use inside your xml.

查看更多
等我变得足够好
5楼-- · 2019-08-08 13:28

you can set an onClick but I think thats about it

查看更多
登录 后发表回答