Fat Monk
Fat Monk

Reputation: 2265

How do I get the correct Context for an OnClickListener?

I'm trying to open a custom dialog when a user clicks on a LinearLayout using the following code:

    each_pays = (TextView) findViewById(R.id.each_pays);

    each_pays_vert.setOnClickListener(new LinearLayout.OnClickListener() {
        @Override
        public void onClick(View _v) {
            // custom dialog
            final Dialog multiples_dialog = new Dialog(this);
            multiples_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            multiples_dialog.setContentView(R.layout.multiples_dialog);

            Button closeMultiplesDialogButton = (Button) multiples_dialog.findViewById(R.id.close_multiples_button);
            // if button is clicked, close the custom dialog
            closeMultiplesDialogButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    multiples_dialog.dismiss();
                }
            });

            multiples_dialog.show();
        }
    });

The custom dialog code etc works elsewhere (when run from an option menu item click, for example), but when I try it here I get a compile time error Error:(303, 71) error: incompatible types: Intent cannot be converted to Context.

The error is in the line:

final Dialog multiples_dialog = new Dialog(this);

If I replace this with getApplicationContext() I get a run time crash.

I'm confused.

Upvotes: 0

Views: 410

Answers (2)

ianhanniballake
ianhanniballake

Reputation: 200010

You can get a Context from a View by using getContext():

final Dialog multiples_dialog = new Dialog(_v.getContext());

Upvotes: 1

Christian
Christian

Reputation: 4641

Your declaration is inside of a Object-Declaration (OnClickListener). So this is not your Activity in this case, but the OnClickListener.

Three options to work around:

  • reference the activity for example with final Dialog multiples_dialog = new Dialog(MainActivity.this)
  • put the code to show the dialog in a separate function in your Activity and call that function in your OnClickListener.
  • save a reference to the Context to be used within the OnClickListener, (mark it as final). This option would look something like this:

'

each_pays = (TextView) findViewById(R.id.each_pays);
final Context ctx = this;
each_pays_vert.setOnClickListener(new LinearLayout.OnClickListener() {
    @Override
    public void onClick(View _v) {
        // custom dialog
        final Dialog multiples_dialog = new Dialog(ctx);
        ...

Note: the Application Context can not be used for any UI-actions. This is the reason of the crash when using getApplicationContext().

Upvotes: 1

Related Questions