Difference between myactivity.this , myactivity.cl

2019-05-26 17:56发布

问题:

I have been trying to use Intent method in my program , the code shows no error when I use myactivity.this ... when I use the other two (myactivity.class or this),eclipse shows an error.

Intent i = new Intent(myActivity.this,myActivity2.class);
startActivity(i);

When I use myactivity.class or this in the first param,

Eclipse shows an error of Constructor Intent not defined. Why is that, can anyone explain?

回答1:

myActivity.this == Refrence to context


myActivity2.class == Reference to class, this is its class name


this == It is Current Type, say if you are in Thread then it is Thread Type; if you are in Activity then it is Activity Type; if you are in your custom class say CAR then it is CAR type

When you do the this then you get an error because you must not be in main thread in this you can use getApplicationContext()

When you use myActivity.this It Knows that it will be started from this activitie's context.



回答2:

Let me give you the answer of:

When i use myactivity.class or this in the first param ,Eclipse shows an error of Constructor Intent not defined.

Reason you got error is that you are supposed to pass valid parameters to the Intent Constructor that you are trying to invoke. See this: LINK Which are

  1. A Context of the application package implementing this class.
  2. The component class that is to be used for the intent.

And as you mentioned, you tried myactivity.class , refering to KITKAT'S answer this parameter is not valid enough to get passed to the Intent constructor.

As for this is concerned, you shouldn't get any compile error, if you are within valid activity context.



回答3:

The first param is for the current activities context therefore this or Activity.this or getApplicationContext will do. and the second param refers to the class name where you want to move to. That is why .this in the first param and .class in the second. Hope you got it now.



回答4:

Maybe you are writing this code in another object ,like in OnClickListener ,thus this is representing the current object of OnClickListener not the MainActivity class. That's why you should use MainActivity.class to reference to main Activity. this in this context is representing the object of OnClickListener.