What is Activity in Android

25 Oct 2013, 01:10 PM


Activity is a most important concept of Android development. It represents the screen in an application the user interacts with. You can use it in different ways as floating window or embedded inside of another activity etc. The class must be inherited from Activity class for your activity. extends keyword is used for inheritance in java. When you create a new project for android mobile it creates a one main activity for you. The code of the activity class is given below.

 public class MainActivity extends Activity {

	protected void onCreate(Bundle savedInstanceState) {

	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;


onCreate method is used to initialize your activity. We usually call setContentView() method to define the layout for the activity and also get UI controls using findViewByid() that are required to interact programmatically.

super.onCreate() means call the onCreate method of base class. Super is used to access the base class in java. The layout that is associated with this activity is in activity_main.xml. You can get the id of that resource using R.layout.activity_main. R is the auto generated class which maintains the resources and we use it to access to resources in code. setContentView(R.layout.activity_main) sets the layout for activity.

onCreateOptionsMenu() method is used to handle the menu for that activity.

Access Control/View in Activity

After setting the content view of the activity, you can get control using findViewById (viewId) method. It takes the view/control id as a parameter and returns the view that is found. View is the base class for widgets, which are used to create interactive UI components (buttons, text fields, etc.). We need to cast the view into the original widgets.

 Button btnPhoneCall = 	(Button)findViewById(R.id.btn_phone_call);
 EditText txtName = (EditText)findViewById(R.id.txt_name);

In above sample code findViewById(R.id.btn_phone_call) finds the button having id passed as parameter and finds the EditText by id. Now after finding we can use these Views/Controls in our code.

About Blog
What is the Activity in Android development and how you use it in your code.

Date 25 Oct 2013, 01:07 PM
Views 2,653