DialogInterface vs View OnClickListeners

Why can't I have both imports for OnClickListener . I already import android.view.View.OnClickListener; but when I want to add import android.content.DialogInterface.OnClickListener; this gives me an error:

Import android.content.DialogInterface.OnClickListener collides with another import statement

That is why, for example, I have to write the full OnClickListener namespace when I need to implement DialogInterface OnClickListener ( OnClickListener

 .setPositiveButton(R.string.ok, new android.content.DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) 

Can someone explain this to me? I apologize if this is a stupid question.

+6
source share
2 answers

You cannot import two classes with the same name into the same file. If you import two classes named X and you request X , the compiler does not know which class you are accessing. There is a good compromise in these situations. You can replace this import ...

 import android.content.DialogInterface.OnClickListener; 

Using this import ...

 import android.content.DialogInterface; 

Then, when you need to access this particular interface, you can do something like this ...

 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { ... }) 

This works because DialogInterface is an interface with a nested static interface called OnClickListener . It should be a little better before our eyes, and this solves the problem of name clashes.

+10
source

I assume that since some classes (e.g. AlertDialog ) work with DialogInterface.OnClickListener , where the OnClick method takes two parameters:

Options: Dialog Box . The clicked dialog.
paramAnonymousInt - a button is pressed (for example, DialogInterface.BUTTON1) or item position.

While the OnClick method from the View.OnClickListener interface accepts only one:

Options:
v - view that has been clicked.

0
source

Source: https://habr.com/ru/post/951655/


All Articles