简体   繁体   中英

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.

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().

您可以使用getContext()View获取Context

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

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