If you have followed previous tutorial, you must be ready to create the first Activity.
Before starting let’s have a quick overview of what activity is in android developer site.
Well, let’s create our first Activity. Create a package and class in src folder as shown in the picture below.
Lets turn it into an Activity by extending it from Activity class and creating onCreate() method. It is the first method that gets executed when the activity starts.
package com.technoguff.tutorial;
import android.app.Activity;
import android.os.Bundle;
public class HelloWorldActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
Now our activity is created. Next thing we have to do is notify the AndroidManifest file that we have an activity which needs to be started when the app is launched.
Open AndroidManifest File and select Application Tab, click on add and choose Activity. For name Browse the existing HelloWorldActivity.
Similarly selecting the Activity node add new node called Intent Filter, then under intent filter node add new nodes called Action and category with values Main and launcher respectively. We will get familiar with intent-filters, categories in this tutorial. Here category LAUNCHER insures that the launcher icon is created for this activity and MAIN action is for running this activity when the app starts.
Alternatively, this can be done directly editing the code from AndroidManifest.xml tab by typing following code inside the Application tag.
<activity android:name=“com.technoguff.tutorial.HelloWorldActivity”>
<intent-filter android:label=“@string/app_name” android:icon=“@drawable/ic_launcher”>
<category android:name=“android.intent.category.LAUNCHER”/>
<action android:name=“android.intent.action.MAIN”/>
</intent-filter>
</activity>
Now we have successfully created our first activity and our application is ready to run. But we don’t yet have any ui elements added. If you run your application at this stage you will just see an empty activity. So let’s add a Textview to our Activity.
package com.technoguff.tutorial;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloWorldActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tvHello = new TextView(this);
tvHello.setText(“Hello World”);
setContentView(tvHello);
}
}
When we run the app we can see the textView displaying “Hello World”. As shown in the picture below.