Android中的事件需要监听器和处理程序。这一点很明显,我们在Java类中看到该侦听器中有Onclicklistener和Onclick方法。
然而,我对XML Onclick方法感到困惑,因为它没有Onclicklistener。它们总是必要的,还是隐藏在这种情况下的倾听者?
<Button
android:Onclick="myMethod"
/>
public void myMethod(View view)
{
//do magic here
}
基本上,当在attributes (like layout_width, onClick and so on)
的创建过程中解析View
时,如果在onClickListener
中设置了此属性,则会为此View
创建XML
。你可以查看for example here,因为它是开源的。
请记住,我正在查看View类,因为Button
扩展TextView
和TextView
扩展View
。
为了进一步解释:当您通过View
创建XML
时,将解析所有属性。然后是properties of the View are set according to those attributes
。你也可以在定义custom View
时自己做。
简单回答您的问题:是的,在创建视图期间,在XML后面隐藏了一个onClickListener
在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
}