Reputation: 59
I'm learning some android development. The following is just a simple code of a multi-screen app for users to click and to change to another screen.
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView redio = (TextView) findViewById(R.id.activity_redio);
redio.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
Intent redioIntent = new Intent(MainActivity.this, redio.class);
startActivity(redioIntent);
}
}
);
}}
It works well. But I have a question about the 'startActivity(redioIntent);' method. Unlike setOnClickListener() method or other general methods in JAVA, I don't need to declare a new instance in order to use it. I wonder why? Moreover, how do I distinguish which methods require declaring new instances and which don't?
Another question is, When creating an new Intent, What does 'this' referees to and what does redio.class mean? I checked the documentation on android developer. It says MainActivity.this is an context. But what is context? And why does Intents need context and class to creat?
Upvotes: 2
Views: 82
Reputation: 3258
It's because your class extends AppCompatActivity
These methods come from AppCompatActivity
by inheritance.
Upvotes: 2
Reputation: 71
It has to do with the inheritance and superclasses. In situations where you have to specify an instance of a class and then a method to call (e.g. ExampleClass.exampleMethod();), you're calling the exampleMethod() method from the ExampleClass class (probably obvious). When you don't specify a class, you're calling that method from the current class, or (importantly) any superclass. Because you're extending AppCompatActivity, AppCompatActivity is a superclass of MainActivity, and the public variables, classes, and methods declared in AppCompatActivity (and any of its superclasses) are inherited into the current class.
Look at the Java Tutorial for a more comprehensive explanation.
Upvotes: 0
Reputation: 537
This is because the class you're writing in, MainActivity, is extending the class AppCompatActivity. You can think of AppCompatActivity as being one page, and you glued MainActivity to the bottom and continued writing. All of the methods in AppCompatActivity can be accessed as if you wrote them in MainActivity, and you can also overwrite/override these existing methods (for example, onCreate is a method declared in AppCompatActivity). So, since these methods are "in the same class," you don't need to reference another class to call them.
Upvotes: 0