gpt4 book ai didi

java - setOnClickListener 匿名类?

转载 作者:行者123 更新时间:2023-11-30 01:00:02 25 4
gpt4 key购买 nike

我是 android 开发的新手,我意识到在真实世界的示例中使用所有界面比在试图向您展示如何使用界面的示例代码中使用它们要困难得多。

因为我想理解我输入的每一行,所以我将从这里开始:

Button clearButton = (Button) findViewById(R.id.buttonClear);

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

第一行很简单,我只是根据 xml 中的 id 将按钮分配给按钮对象,但我不了解监听器,只是我得到了 clearButton 对象,我将使用其中一个方法, setOnClickListener,然后在我传递匿名类的参数中我想覆盖哪种行为,但是 View.OnClickListener() 方法不是对象吗?我在函数内部编写类?

new View.OnClickListener() {
@Override
public void onClick(View v) {
}

这看起来像是一个包含内联类的函数 OnClickListener 吗?

最佳答案

这叫做观察者模式。您将您的监听器注册到 UI 并告诉它在发生某些事情时调用您的代码;在这种情况下,用户点击了您的清除按钮。

所以:

这很简单,您正在创建一个按钮对象并将其附加到您的布局文件中。

Button clearButton = (Button) findViewById(R.id.buttonClear);

下一步:

让我重写一下:

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

为此:

//First let's create an implementation of this interface.
// These are also refereed to as callback interfaces as
//the methods in their implementation are called as whenever
//something happens on the UI. In this call onClick is the callback method.


private class MyButtonClicklistener implements View.OnClickListener
{
@Override
public void onClick(View v)
{
//Do something on the button click
}

}

创建监听器实例

MyButtonClickListener mListener = new MyButtonClickListener();

最后注册你的监听器。现在,您要告诉您的 UI 在有人单击清除按钮时调用 mListener 对象的 onClick 方法。

clearButton.setOnClickListener(mListener);

关于java - setOnClickListener 匿名类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39560565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com