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

孤街浪徒 提交于 2019-12-24 02:56:14

问题


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?


回答1:


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




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/9138875/toast-maketextgetapplicationcontext-string-toast-length-long-here-ge

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!