Difference between myactivity.this , myactivity.class, this

£可爱£侵袭症+ 提交于 2019-12-22 13:53:02

问题


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.



来源:https://stackoverflow.com/questions/18941007/difference-between-myactivity-this-myactivity-class-this

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