Searene
Searene

Reputation: 27644

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

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?

Upvotes: 2

Views: 11555

Answers (3)

SHIVAM ARORA
SHIVAM ARORA

Reputation: 1

new OnClickListner() is an anonymous class that implements onclick interface and this refers to the instance of the anonymous class. Rather use "Your_Activity_Name.this" to refer to the current context of your activity.

Upvotes: -1

jeet
jeet

Reputation: 29199

Iin this case this is indicating OnClickListener instance, to create view, or other UI stuff, you need to get context, this can be done by following different methods:

getApplicationContext();
ContextMenuResourcesActivity.this;
v.getContext();

Upvotes: 0

William Melani
William Melani

Reputation: 4268

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

Upvotes: 5

Related Questions