如果没有事件监听器,XML onClick如何工作?

问题描述 投票:0回答:2

Android中的事件需要监听器和处理程序。这一点很明显,我们在Java类中看到该侦听器中有Onclicklistener和Onclick方法。

然而,我对XML Onclick方法感到困惑,因为它没有Onclicklistener。它们总是必要的,还是隐藏在这种情况下的倾听者?

<Button
  android:Onclick="myMethod"
/>

public void myMethod(View view)
{
  //do magic here 
}
android xml events onclick onclicklistener
2个回答
1
投票

基本上,当在attributes (like layout_width, onClick and so on)的创建过程中解析View时,如果在onClickListener中设置了此属性,则会为此View创建XML。你可以查看for example here,因为它是开源的。

请记住,我正在查看View类,因为Button扩展TextViewTextView扩展View

为了进一步解释:当您通过View创建XML时,将解析所有属性。然后是properties of the View are set according to those attributes。你也可以在定义custom View时自己做。

简单回答您的问题:是的,在创建视图期间,在XML后面隐藏了一个onClickListener


0
投票

在Java代码或XML中设置OnClickListener没有区别。如果要通过XML设置侦听器,则必须在Java代码中实现相应的方法。当您通过XML设置侦听器时,然后在View构造函数中解析并自动为您设置侦听器:

case R.styleable.View_onClick:
        ...
    final String handlerName = a.getString(attr);
        if (handlerName != null) {
            setOnClickListener(new DeclaredOnClickListener(this, handlerName));
        }
    break;

它看起来像这样。 XML代码:

<Button android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Text"
    android:onClick="onClickFromXml" />

然后在Java代码中:

public void onClickFromXml(View v) {
    // your click listener implementation
}
© www.soinside.com 2019 - 2024. All rights reserved.