Toast.makeText(getApplicationContext(), "String", Toast.LENGTH_LONG); ==>Here getApplicationContext() cannot change to "this"?

11,245

When you create a new OnClickListener, you are creating a anonymous class which implements a particular interface. Thus, this does not refer to the Activity, since you are actually in another object.

Here's some more info on the subject Anonymous classes vs delegates

Share:
11,245
Searene
Author by

Searene

A social nerd.

Updated on June 29, 2022

Comments

  • Searene
    Searene almost 2 years

    First the format of Toast.makeText():

    public static Toast makeText (Context context, CharSequence text, int duration) the first argument is Context, the function getApplicationContext() also return the current context, everything is ok, but IMO, the getApplicationContext() can also be replaced with this, just as follows:

    public class ContextMenuResourcesActivity extends Activity {
        /** Called when the activity is first created. */
    
        private Button b1;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
        b1 = (Button)findViewById(R.id.button1);
        final int l = Toast.LENGTH_LONG;
        final String s1 = "some string";
        b1.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    Toast t1 = Toast.makeText(this, s1, l);
                    t1.show();
                }
            });
        }
    }
    

    IMO this stands for the class ContextMenuResourcesActivity, which extends Context, so it can replace the first argument which demands for Context, but I failed, can anyone explain why?