Android - Activity Tutorial
Below is the screenshot of user interface of an LoginActivity.

How to create an Activity
To create an activity you must create a subclass of Activity class. For example creating a LoginActivity:

In your subclass you need to implement some callback methods. Activity can exist in different lifecycle states like pause state, resume state, stopped state. These lifecycle states are managed by callback methods. Below is the list of callback methods.
Activity represents a single screen with a user interface. Activity is an essential component which provides a screen with which user of your application can interact.
An application can have multiple screens. These screens are represented with the help of an activity. For example:
An application can have multiple screens. These screens are represented with the help of an activity. For example:
- Login Screen
- Registration Screen
- Home Screen
Below is the screenshot of user interface of an LoginActivity.
How to create an Activity
To create an activity you must create a subclass of Activity class. For example creating a LoginActivity:
1
2
| public class LoginActivity extends Activity {} |
In your subclass you need to implement some callback methods. Activity can exist in different lifecycle states like pause state, resume state, stopped state. These lifecycle states are managed by callback methods. Below is the list of callback methods.
| onCreate() |
Called when activity is first created.
|
| onPause() |
Activity is being paused and it is no long visible to user.
|
| onStop() |
Activity is being stopped.
|
| onResume() |
Activity is being resumed.
|
| onDestroy() |
Activity is being destroyed.
|
We will learn more about Lifecycle of an activity in another tutorial. Now the most important method you need to implement is onCreate().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| package com.example.activitykb4dev;import android.os.Bundle;import android.app.Activity;public class LoginActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); }} |
In the above code snippet. LoginActivity is the base class of Activity.
How to include xml layout file in Activity
In onCreate() method, there is a function setContentView() in which you need to pass the reference of layout xml file. As you develop your application some files are automatically generated. There is one R.java automatic generated file which helps to link xml layout and java activity. You can see that as a reference we have passed R.layout.activity_login.
1
| setContentView(R.layout.activity_login); |
So whenever android system runs our activity, it first looks for the onCreate() system call which helps to create the activity by supplying the layout file.
In the next tutorial we will learn about event handling in activity.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.