Vous êtes sur la page 1sur 52

AN ACTIVITY IN ANDROID

ACTIVITY

What Is An Activity ?
An Activity is a window that contains the user interface of our application. An Android application can have one or more activities.

Just like an applet, an Activity also has several stages in its life cycle

How an Activity is created ?

To create an Activity we create a java class that extends the Activity class available in the package android.app

MainActivity.java
package com.example.myfirstapp; import android.os.Bundle; import android.app.Activity; import android.view.Menu; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }

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

Code Explained
The onCreate() method is called by the Android system when our Activity starts It is where we should perform all initialization and UI setup. It is compulsory for a programmer to call the super.onCreate() method so that Android Run Time can perform basic set up for our Activity

Code Explained
After initial setup our class has to load the user interface elements which can be done in 2 ways: 1. Using Programmatic layout

2. Using XML based layout In the the first approach we use java code to set layout of our components

Programmatic Layout Demo


package com.example.demo2; import import import import android.os.Bundle; android.app.Activity; android.view.Menu; android.widget.TextView;

public class MainActivity extends Activity {


@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); tv.setText("My First Android App"); setContentView(tv); }

Programmatic Layout Demo


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

Code Explained
The first line creates an Object of TextView which is a non editable text, similar to JLabel component of java swing.

The TextView constructor accepts an Android Context instance as its parameter. A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on.

Code Explained
The Activity class inherits from Context, and because our MainActivity class is a subclass of Activity, it is also a Context. So, we can pass this as our Context reference to the TextView. In the next line we call the setText() method to set text in TextView

Code Explained
Finally, we pass the TextView to setContentView() in order to display it as the content for the Activity UI. If our Activity doesn't call this method, then no UI is present and the system will display a blank screen.

Code Explained
Although we can use this type of Programmatic Layout in our code but the Android specification does not recommend it.

This is because small changes in the layout can result in big source code headaches.

Code Explained
Thus the preferred approach is to use XML based layouts so that event handling code is separated from user interface code.

The user interface by default is defined in a file called activity_main.xml and to load this user interface we call the method setContentView(R.layout.activity_main);

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> </RelativeLayout>

Explanation Of activity_main.xml
The first line is the regular xml directive indicating the XML version along with the tag <RelativeLayout>.
Layout is a technique to arrange our components on the page. There are several layouts available like LinearLayout,TableLayout,AbsoluteLayout,
The default is RelativeLayout

Code Explained
In the <RelativeLayout> tag we also use the xmlns:android with the value http://schemas.android.com/apk/res/a ndroid

It is the default setting and compulsory to be able to use other elements in activity_main.xml

Code Explained
After that we have 2 attributes :
android:layout_width="match_parent android:layout_height="match_parent"

The layout_width and layout_height components are set to match_parent which tells the layout to stretch the activity size to match its container which is the screen itself

Code Explained
Following it we have 4 attributes:
android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin"

These attributes set the distance between the contents and the borders of the relative layout window i.e the Activity. Their values have been set to attributes defined in dimens.xml

Code Explained
TextView describes an area where text can be displayed . It resembles the Labels in java swings. Within the TextView definition: android:layout_width=wrap_content" android:layout_height="wrap_content" define a width and height for the TextView box. android:text="@string/hello"provides some text to display in the TextView. The actual string is defined in a separate file, res/values/strings.xml.

Providing Id To Views
The components which we create in our XML file might need to be accessed in java code. In this case one more important property has to be set called as android:id To set it the general syntax is: android:id=@+id/someid Also when we set it the R.java file also gets updated

After creating views(gui components) in XML file, we frequently need to refer to them in our java code to manipulate their properties or for other tasks. This can be done using the method findViewById() provided by the Activity class

Accessing Views In Java Code

Its prototype is: public View findViewById (int id) The argument passed to this method is id of the component as specified in R.java. For example if we have a TextView with id t1 set in XML file then the call would be: findViewById(R.id.t1);

Accessing Views In Java Code

Accessing Views In Java Code


The return value of findViewById() is a reference to the specified view if it is found , otherwise it returns null. Moreover since return type of the method is View we need to downcast it to specific component. So the complete call would be:
TextView tv; tv=(TextView)findViewById(R.id.t1);

Example 2
Write an android mobile app to display current date and time in a TextView.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/txtDisplay"/> </LinearLayout>

DisplayDateTimeActivity.java
package alex.cruger.androidapp; import java.util.Date; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class DisplayDateTimeActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView tv=(TextView)findViewById(R.id.txtDisplay); Date today=new Date(); tv.setText(today.toString()); } }

The Button View


Buttons in android can be created using the Button class , which is a derived class of TextView. This class is available in the package android.widget. Just like other GUI programming languages, Buttons in android also are the most important components for generating events.

Creating A Button
To create a Button to the Activity, we can use the following code in XML file:
<Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click Me" />

Positioning The Button


Writng the above code will place the button at the top left corner which may overlap it on an existing control. To avoid this we must tell android to place the newly created BUTTON view towards left,right,below or above the present control.

Positioning The Button


For this android provides us 4 attributes of Button 1.android:layout_toLeftOf 2.android:layout_toRightOf 3.android:layout_below 4.android:layout_above The value assigned to these attributes is the id of the component with respect to which the button needs to be placed

Positioning The Button


So the complete code becomes <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello" android:id="@+id/msg"/>

<Button android:id="@+id/mybtn" android:text="Click me" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/msg />

Event Handling
Events are the actions a user takes at the run time of our app. Like clicking a Button, Tapping on screen, typing text in EditText(TextField) etc. Event Handling Now if our application wants to respond to those events i.e. execute some piece of code in response to the event then we perform Event Handling

To perform event handling with Button, android follows the same approach as Java. Here are major steps in handling Button click event:
1. Implement the interface OnClickListener 2. Override the onClick() method 3. Register the respective Button as source and implementing class as listener by calling setOnClickListener()

Event Handling With Button

Example 3
Write an android mobile app to display a Button titled Click Me and when it is clicked the Buttons title should display current Date and Time.

main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:id="@+id/btn1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click Me" /> </LinearLayout>

DisplayDateTimeActivity.java
package alex.kruger.androidapps; import java.util.Date; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class DisplayDateTimeButtonActivity extends Activity implements OnClickListener { private Button b1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); b1=(Button)findViewById(R.id.btn1); b1.setOnClickListener(this); }

public void onClick(View arg0) { Date today=new Date(); b1.setText(today.toString()); } }

Example 4
Write an android mobile app to display a Button titled Click Me and when it is clicked a TextView should display number of times button has been clicked.

main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.co m/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" >
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" />

<TextView android:id="@+id/t1" android:layout_width="302dp" android:layout_height="wrap_content" android:text="0" /> <Button android:id="@+id/button1" android:layout_width="99dp" android:layout_height="32dp" android:text="Click Me" /> </LinearLayout>

ClickCountActivity.java
package kapoor.sachin.androidapps; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class ClickCountActivity extends Activity implements OnClickListener { private TextView tv; private Button b1; private int count;

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv=(TextView)findViewById(R.id.t1); b1=(Button)findViewById(R.id.button1); b1.setOnClickListener(this); } public void onClick(View arg0) {

++count; tv.setText(String.valueOf(count)); } }

Handling Multiple Sources


If we have set multiple sources(like buttons) for a single event then we use the method getId() of the View class whose object is passed as an argument to the method onClick() . This method returns the id of the widget which triggered the event. The prototype of the method is: public int getId() This id can then be compared with R.id values to determine the specific widget.

Example 5
Write an android mobile app to display 2 Buttons titled Increase and Decrease which when clicked increment and decrement the counter accordingly.

main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android " android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" />

<TextView android:id="@+id/t1" android:layout_width="232dp" android:layout_height="wrap_content" android:text="0" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="34dp" android:text="Increase" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="32dp" android:text="Decrease" /> </LinearLayout>

MultiSourceActivity.java
package kapoor.sachin.androidapps; import import import import import import android.app.Activity; android.os.Bundle; android.view.View; android.view.View.OnClickListener; android.widget.Button; android.widget.TextView;

public class MultiSourceActivity extends Activity implements OnClickListener{ Button b1,b2; TextView tv; int count;

@Override public void onCreate(BundlesavedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); b1=(Button)findViewById(R.id.button1); b2=(Button)findViewById(R.id.button2); tv=(TextView)findViewById(R.id.t1); b1.setOnClickListener(this); b2.setOnClickListener(this); }

public void onClick(View v) { int source=v.getId(); switch(source) { case R.id.button1: ++count; break; case R.id.button2: --count; break; } tv.setText(String.valueOf(count)); } }

Alternate Way Of Event Handling


Rather than using the OnClickListener we have an alternate way of handling events also using XML file. Its as follows: 1. Assign a method to your button in the XML layout, using the android:onClick attribute. For example: <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:text=Click Me" android:onClick=myClick" />

2. Now, when a user clicks the button, the Android system calls the activity's myClick(View) method. In order for this to work, the method must be public and accept a View as its only parameter. For example: public void myClick(View v) { // code } The View passed into the method is a reference to the widget that was clicked.

Vous aimerez peut-être aussi