有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java setOnClickListener匿名类?

我是安卓开发的新手,我意识到在现实世界的示例中使用所有接口要比在示例代码中使用它们困难得多,这些示例代码试图向您展示如何使用接口

由于我想了解我键入的每一行,我将从以下内容开始:

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

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

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

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

这看起来像是一个函数OnClickListener,它包含一个内联类,所以


共 (1) 个答案

  1. # 1 楼答案

    这叫做观察者模式。你把你的监听器注册到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();
    

    最后注册你的听众。现在,你告诉你的用户界面,只要有人点击清除按钮,就调用mListener对象的onClick方法

    clearButton.setOnClickListener(mListener);