我是 Android 开发新手,我意识到在现实世界的示例中使用所有接口(interface)比在试图向您展示如何使用该接口(interface)的示例代码中使用它们要困难得多。
因为我想理解我输入的每一行,所以我将从这里开始:
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/