java - "this"Android实现多接口(interface)时的关键字

标签 java android this android-button

<分区>

我知道 this 关键字是对当前对象的引用,但我对何时在 Android 应用程序中实现多个接口(interface)感到困惑。

例。我像这样创建新的 Button:

public class Example extends Activity implements View.OnClickListener, View.OnTouchListener {

@Override
...
// override OnClick and OnTouch

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // 'this' refer to context in Activity
    Button button = new Button(this);

    // 'this' refer to OnClickListener
    button.setOnClickListener(this);

    // 'this' refer to OnTouchListener
    button.setOnTouchListener(this);
}

}

程序如何知道要引用什么对象?

当创建新的 Button 而不是 OnClickListener 时,程序如何知道必须将 Activity 中的上下文作为参数传递?

谢谢。

最佳答案

this 引用您的示例

关于你在这里写的:

// 'this' refer to context in Activity
Button button = new Button(this);

// 'this' refer to OnClickListener
button.setOnClickListener(this);

// 'this' refer to OnTouchListener
button.setOnTouchListener(this);

其实都是指一个Example一个ActivityOnClickListenerOnTouchListener.

关于java - "this"Android实现多接口(interface)时的关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24236767/

相关文章:

c++ - 如果字段通过引用传递,则类字段可以在 const 方法内修改吗?

java - Spring Boot : error =“invalid_grant” , error_description =“Bad credentials”

java - 在子类的方法中本地调用父类(super class)方法时使用 "super"关键字或使用父类(super class)实例?

android - 您的 APP_BUILD_SCRIPT 使用 Android ndk-build 指向未知文件

android - 使用 setcontentview 两次

java - 有什么方法可以在 Java 中返回多态 this 吗?

Javascript 无法从使用此调用的方法设置属性

java - 使用qt通过套接字发送图像并使用java读取它

java - 在 AOP 注释切入点上获取注释

java - 发送带有 boolean 值的模型类以改进有时不接受该 boolean 值的端点