究竟如何在Android:的onClick XML属性从setOnClickListener有什么不同?有什么不同、属性、如何在、Android

2023-09-11 10:28:52 作者:一眼爱人 .

这是我读过你可以通过两种方式分配的onClick 处理程序的按钮。

From that I've read you can assign a onClick handler to a button in two ways.

使用安卓的onClick ,你只需要使用一个公共方法的名称与签名XML属性无效名(查看V)或使用 setOnClickListener 方法,你传递实现了 OnClickListener 接口的对象。后者往往需要其个人而言,我不喜欢一个匿名类(个人口味),或者定义一个实现一个内部类中的 OnClickListener

Using the android:onClick XML attribute where you just use the name of a public method with the signaturevoid name(View v) or by using the setOnClickListener method where you pass an object that implement the OnClickListener interface. The latter often requires an anonymous class which personally I don't like (personal taste) or defining an internal class that implements the OnClickListener.

通过使用XML属性,你只需要定义一个类的方法,而不是让我 想知道如果同样可以通过code,而不是在XML布局来完成。

By using the XML attribute you just need to define a method instead of a class so I was wondering if the same can be done via code and not in the XML layout.

推荐答案

没有那是不可能通过code。 Android的只是实现了 OnClickListener 您在定义安卓。的onClick =someMethod的属性

No that is not possible via code. Android just implements the OnClickListener for you when you define the android:onClick="someMethod" attribute.

这两个code片段是完全一样的,但仅仅实施了两种不同的方式。

Those two code snippets are totally the same but just implemented in two different ways.

code实现

Button btn = (Button) findViewById(R.id.mybutton);

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        myFancyMethod(v);
    }
});

// some more code

public void myFancyMethod(View v) {
    // does something very interesting
}

以上是一个 OnClickListener 的code实现。而现在的XML实现。

Above is a code implementation of an OnClickListener. And now the XML implementation.

XML实施

<?xml version="1.0" encoding="utf-8"?>
<!-- layout elements -->
<Button android:id="@+id/mybutton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Click me!"
    android:onClick="myFancyMethod" />
<!-- even more layout elements -->

现在在后台的Andr​​oid并没有别的比Java code上的点击事件调用你的方法。

Now in the background Android does nothing else than the Java code calling your method on a click event.

请注意,与上面的XML,Android将查找的onClick 方法 myFancyMethod()只在当前活动。这个,如果你使用的是碎片的,因为即使添加上述使用的是片段的XML记住,Android将不会寻求在的.java 用于添加XML片段的文件。

Note that with the XML above, Android will look for the onClick method myFancyMethod() only in the current Activity. This is important to remember if you are using fragments, since even if you add the XML above using a fragment, Android will not look for the onClick method in the .java file of the fragment used to add the XML.

另一个重要的事情,我注意到。你刚才提到你没有preFER匿名的方法的。你的意思是说你不喜欢匿名类

Another important thing I noticed. You mentioned you don't prefer anonymous methods. You meant to say you don't like anonymous classes.