Passing arguments/parameters in android
Sorry if this is a stupid question, but I searched a lot and I couldn't find anything
I dont understand this code snippet fully --
Intent intent = new Intent (this, MainActivity.class)
开发者_如何学编程
what I dont understand about that line is the (this, MainActivity.class)
part. Will someone explain please?
Thank you!
It's well documented here:
public Intent (Context packageContext, Class<?> cls)
Since: API Level 1
Create an intent for a specific component. All other fields (action, data, type, class) are null, though they can be modified later with explicit calls. This provides a convenient way to create an intent that is intended to execute a hard-coded class name, rather than relying on the system to find an appropriate class for you; see setComponent(ComponentName) for more information on the repercussions of this.
Parameters
packageContext A Context of the application package implementing this class.
cls The component class that is to be used for the intent.
The arguments for the Intent in this case would be a Context and a Class.
Context is a fantastically useful piece of the Android system that basically allows the program to keep track of what is displayed and where resources are. In some ways you could consider it like System in other... systems. A lot of things require context in order to ensure that everything is working given its loosely coupled nature.
the Class that's required is the compiled version of your .Java files so to run MainActivity.java you would pass MainActivity.Class
Think of the process of using Intents to start Activities as being analogous to instantiating objects using the Java new
keyword. Example...
MyClass.java
public class MyClass {
}
In some other code...
MyClass exampleClass = new MyClass();
In Android Activities are in essence simply just Java classes - they are, however, 'special' classes and as such we don't use new
to instantiate them. Instead we ask the Android system to instantiate them for us.
In the example you give, you are defining explicitly which Activity class to instantiate...
MainActivity.java
public class MainActivity extends Activity {
}
Then in some other code you use the following...
Intent intent = new Intent (this, MainActivity.class);
startActivity(intent);
The call to startActivity(...)
is the way of asking the Android system to instantiate a 'new' instance of MainActivity.
As has been mentioned in the other posts, this method requires passing an Android Context
which in this case is done using this
. What that means is the application component which is requesting to create a new instance of MainActivity
is passing itself as the Context
.
精彩评论