Is there any difference between Activityname.this() & this?

前端 未结 2 768
情书的邮戳
情书的邮戳 2021-01-14 02:16

Is there any difference between Activityname.this() & this in Android?

I am trying to open an activity from same activity with button i

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-14 02:27

    Is there any difference between Activityname.this() & this in Android ?

    This depends on where you are calling it from. If you are inside the Activity, not inside of a listener or inner class like in onCreate then no. They both refer to the Activity context.

    If you are say inside of an onClickListener then yes. this refers to the listener and you need to use ActivityName.this or something like

    someButton.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            Intent i = (v.getContext(), NextActivity.class);   use the button context which will be the same as the activity context
            startActivity(i);
         }
    });
    

    This will be the same as when using a Dialog or AlertDialog, you will want to use ActivityName.this

    This is an answer that talks about the difference of Contexts but there's a better one I will see if I can find

    A great Context explanation

    Edit for more completeness

    AFAIK, getApplicationContext() or ActivityName.this is fine for Toasts. The example in the docs uses getApplicationContext(). But the Toast Docs says

    Parameters context The context to use. Usually your Application or Activity object.

    So there may be certain instances where one is better but I have always used Activity Context and I guess I will until I am corrected on this.

提交回复
热议问题