-->

Android - Can we extends OnClickListener another C

2020-07-24 04:58发布

问题:

public class A extends Activity {
   public void onCreate(Bundle b){
      ~
       Button b1 = (Button) findViewById(R.id.btn);
       b1.setOnClickListener(new B());
      ~
   }
}

public class B extends OnClickListener{
    ~ do something public void onClick() etc..
}

İs it possible or is there an any way to do this?

回答1:

OnClickListener is an interface, so depending on what you want to do with it you can either use:

public interface MyClickListener extends OnClickListener {}

public class MyClickClass implements OnClickListener {}

Looking at your example, I assume that you want the second option:

public class MyClickClass implements OnClickListener {
    @Override
    public void onClick(View v) {
        Log.v("MyClickClass", "b1 clicked!");
    }
}

Use it like this: b1.setOnClickListener(new MyClickClass());