Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DialogInterface vs View OnClickListeners

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

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

This is the reason why, for example, I have to write the full namespace of the OnClickListener when I need to implement a DialogInterface OnClickListener( i.e.

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

                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            })

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

like image 682
Aksiom Avatar asked Aug 13 '13 15:08

Aksiom


1 Answers

You can't import two classes with the same name in the same file. If you import two classes with name X and you ask for an X, the compiler doesn't know which class you're referring to. There is a nice compromise in these situations. You can replace this import...

import android.content.DialogInterface.OnClickListener;

With this import...

import android.content.DialogInterface;

Then when you need to refer to that 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 named OnClickListener. This should be a little nicer on the eyes, and it solves the name collision problem.

like image 66
w0rp Avatar answered Sep 21 '22 23:09

w0rp