简体   繁体   中英

Why OnClickListener interface is not implemented and passed as new in setOnClickListener() method?

I am learning JAVA for Android. I have read that Interfaces should be implemented. But i have confusion here:

final  CheckBox checkbox = (CheckBox) findViewById(R.id.checkbox);
        checkbox.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkbox.isChecked()) {
                    checkbox.setText("I'm checked");
                } else {
                    checkbox.setText("I'm not checked");
                }
            }
        });

we are passing and implementing OnClickListener interface directly here. What is exact reason for this? Please explain this concept in details.

It's because you want to implement it individually for each individual clickable widget. OnClickListener is an inner interface in the View class and logically it would not make sense to make the activity implement it as then any click on the screen even outside of this would trigger unexpected action.

Interfaces alone do not have an implementation. But here what you're actually doing is creating a new anonymous class (a class without a name) that implements the OnClickListener interface and defining the implementation of it all in one place.

As for why you would do this- for very small simple implementations it can be clean, and it prevents you from having dozens of little classes that implement 1 or 2 functions. If the implementation is long it can become difficult to read though. But its never wrong to do it the long way and use a regular class.

Normally we implement OnClickListener like below,

public class MainActivity extends Activity implement OnClickListerner
{
 ....

     view.setOnClickListener(this);                // When we are implemeting OnClickListener

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

When we implement OnClickListener in that case we set it using setOnClickListener(this), here this refers to OnClickListener listener.

However we can do same thing by declaring another way known as anonymous block as below,

CheckBox checkbox = (CheckBox) findViewById(R.id.checkbox);
        checkbox.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkbox.isChecked()) {
                    checkbox.setText("I'm checked");
                } else {
                    checkbox.setText("I'm not checked");
                }
            }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM