Android Studio 中 "View v" 的含义

Meaning of "View v" in Android Studio

我正在尝试在我的 Android 应用程序中实现按钮点击处理。

在包含我的按钮的 XML 布局文件中,我将以下行添加到我的 Button XML 元素中:

android:onClick="handleClick"

我还在使用此布局的 Activity 中定义了具有以下签名的方法:

public void handleClick() { /* ... */ }

但是,当我 运行 我的应用程序使用此代码时,它崩溃了。我能够通过将我的方法签名更新为:

来修复此崩溃
public void handleClick(View v) { /* ... */ }

但我不明白为什么我需要包含这个 View 参数?

这是因为您可能想对 XML 中的 2 个或更多按钮使用 handleClick 方法。

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="handleClick"/>

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="handleClick"/>

在那种情况下,可能不清楚是哪个按钮触发了回调。 View v 可帮助您识别,例如

public void handleClick(View v) {
    if (v.getId() == R.id.button1) {

    } else if(v.getId() == R.id.button2) {

    }
}

提供的 View 参数代表接收点击事件的 View。如果您为多个 View 重用 handleClick 方法,这可能很有用(在这种情况下,您可以检查传递给该方法的 Viewid 以确定哪个View 被点击,如 所示)。

您必须在定义您的方法时包含此 View 参数,即使您没有在您的点击逻辑中使用它。这是因为 reflection is used to locate the method corresponding to the name you supplied in XML, and the method name, parameter count, and parameter types are all required to uniquely define a method in Java. Check out this section of the View source code 要确切地了解此反射查找的工作原理!

View v 是 xml 文件的对象,它在 onCreate 方法中引用。 要引用 xml 中的任何组件,您必须使用 v 来获取组件的 ID。

条件

You have give id to the component in xml if you want to use onClick in your class file.