Sunteți pe pagina 1din 60

5.

1 Android activity example

Android activity
One of the fundamental building block of Android app development is Activity. It is just like a
single screen with user interface. ContextThemeWrapper is the super class of Android activity.
Activity is the main entry point of an Android app just like main method of a program written in
Java or C++. An activity interacts with user so it creates a window to place UI elements. An
Android application can contain several activities means many different screens that can interact
with each other.

Activity life cycle


Android activity has its own life cycle during its life in Android app. Activities are stored and
managed in a stack called activity stack. New activity comes at the top of stack and becomes
running, while previous remains below to the new activity in stack. When the top activity in the
stack exits, the lower to the top becomes active.

States of Android activity


An activity has four states

Running: Activity at the top of the stack is in running or active state means it is at the
foreground of the screen.

Paused: An activity which is alive but not focused is in the paused state. (That is as a pop-up
message shown on the activity).

Resumed: When a paused activity becomes active it is refreshed and started again.

Stopped: An activity which is no longer visible on the screen is in the stopped state.

Call back methods of Android activity

An Android activity implements following call back methods

OnCreate(): This is first call back method of an Android activity. It is called when an activity is
created. This is where all you set all stuffs like button and views.

OnStart(): It is second call back. It is called when the activity is visible on the screen.

OnResume(): This is called after OnStart() if the activity comes to foreground. This is when
user starts interacting with the activity.

OnPause(): This is followed by OnResume(). This is called when a previous activity is resumed.

OnStop(): It is called when another activity is resumed then this activity is no longer visible. It
becomes hidden.

OnDestroy(): This is the final call back when the activity is finished.

The following diagram shows complete life cycle of an Android activity.


Android activity life cycle
Rectangles in the figure represent the 6 call back methods.

Android activity example

Here is the example of Android activity. Open your Android Studio and create a new project.
New project wizard will allow you to create a new activity.

package com.example.admin.androidactivity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

public class ActivityExample extends AppCompatActivity {


@Override
protected void onStart() {
super.onStart();
}

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
protected void onStop() {
super.onStop();
}

@Override
protected void onResume() {
super.onResume();
}

@Override
protected void onPause() {
super.onPause();
}

@Override
protected void onDestroy() {
super.onDestroy();
}
}

5.2 User Interface Designing Layouts

Layout is the way in which things are arranged in a specific manner. Android also provides
different layouts to arrange different components in different manner. Some of them are linear
layout, relative layout, list view, grid view and web view layout etc. Layouts are very important
for the development of UI applications.

5.2.1 Linear layout

Linear layout in Android allows us to arrange components horizontally in a single column or


vertically in a single row. Vertically or horizontally direction depends on attribute android:
orientation. Linear layout is simple and easy to use; it creates a scroll bar if the length of the
window exceeds the length of the screen. Vertically linear layout has only one item per row.
Linear layout has many different attributes which can be used to customize linear layout
according to needs. Following figure shows horizontal and vertical linear layout.
Attributes of linear layout

Following are some attributes of linear layout of Android.


Id: Unique identifier of layout.
Orientation: Attribute to set linear layout orientation as vertical or horizontal.
Layout_Weight: This attribute assigns “importance” value at each component.
Gravity: This attribute shows object position in x-y plan such as center, right, top, bottom and
left.
Weight_sum: This attribute defines the maximum weighted sum.
Divider: draw able to use as a vertical divider between buttons.

Other than these attributes, linear layout has many different constructors.

Constructors of linear layout

Following are constructors of linear layout


LinearLayout(Context context)
LinearLayout(Context context, AttributeSet attrs)
LinearLayout(Context context, AttributeSet attrs, int styleAttribute)
LinearLayout(Context context, AttributeSet attrs, int styleAttribute, int styleRes)

Example of linear layout in Android


Linear layout looks different if the attribute values are set different for two linear layouts, such as
vertical linear layout or horizontal linear layout.

Following example shows vertical linear layout. Here is the activity_linear_vertical.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout android:layout_width="368dp"
android:layout_height="495dp"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:id="@+id/button5"
android:layout_width="301dp"
android:layout_height="wrap_content"
android:text="Button1" />
<Button
android:id="@+id/button6"
android:layout_width="301dp"
android:layout_height="wrap_content"
android:text="Button2" />
<Button
android:id="@+id/button7"
android:layout_width="301dp"
android:layout_height="wrap_content"
android:text="Button3" />
<Button
android:id="@+id/button8"
android:layout_width="301dp"
android:layout_height="wrap_content"
android:text="Button4" />

</LinearLayout>

Here is another example which shows horizontal linear layout. Below is the code for
activity_linear_horizontal.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout android:layout_width="368dp"
android:layout_height="495dp"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button4" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button3" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button2" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button1" />

</LinearLayout>

5.2.1 Relative layout

Relative layout as the name suggests, shows position of components relative to each other. The
position can be specified with respect to consecutive elements or to the parent component.
Relative layout is most flexible layout provided by Android. It lets you position elements on the
screen. By default, it sets all components at the top left of the layout. Following figure shows
how relative layout looks like,

Relative layout attributes


Following are attributes of relative layout.
 Id: Defines if of layout
 Gravity: It specifies position of object in x-y plan.
 IgnoreGravity: It is added to ignore gravity on a specific component.

Relative layout constructors


Relative layout has four different constructors
 RelativeLayout( Contetxt context)
 RelativeLayout( Contetxt context, AttributeSet attrs)
 RelativeLayout( Contetxt context, AttributeSet attrs, int defStyleAttribute)
 RelativeLayout( Contetxt context, AttributeSet attrs, int defStyleAttribute, int
defStyleRes)

Methods of relative layout


Following are several important methods of relative layout
 setGravity(): It sets gravity of the child views as centered, left or right.
 setHorizontalGravity(): Used to positioned elements horizontally.
 setVerticalGravity(): Used to positioned elements vertically.
 requestLayout(): Used to request layout.
 setIgnoreGravity(): Used to ignore gravity of any particular element.
 getGravity(): Used to get the position of elements.
 getAccessibilityClassName(): Returns class name of object.

XML attributes of relative layout


Relative layout has following XML attributes.
 android: layout_above, It position the bottom edge of the given component above the
given component ID.
 android: layout_alignBaseline, It position the baseline of given component above the
baseline of given component ID.
 android: layout_alignBottom, It aligns at the bottom of given component ID.
 android: layout_alignEnd, It aligns at the end of given component ID.
 android: layout_alignLeft, It position the component left to the given component ID.
 android: layout_alignRight, It position the component right to the given component ID.

Relative layout example


Following example shows relative layout in Android. Create an empty activity and drag relative
layout from the palette on to the screen. And then drag your required GUI components. Here is
the xml file.

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout android:layout_width="368dp"
android:layout_height="495dp"
xmlns:tools="http://schemas.android.com/tools"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:id="@+id/S"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText2"
android:layout_marginTop="35dp"
android:layout_toRightOf="@+id/textView"
android:text="SignIn" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView5"
android:layout_below="@+id/textView"
android:layout_marginTop="44dp"
android:text="ID"
android:textColor="@android:color/black"
android:textSize="18sp"
android:typeface="normal" />
<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView2"
android:layout_alignBottom="@+id/textView2"
android:layout_toRightOf="@+id/textView5"
android:ems="10"
android:inputType="textPersonName"
android:text="Enter ID" >

<requestFocus />
</EditText>
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText"
android:layout_alignRight="@+id/editText"
android:layout_below="@+id/editText"
android:layout_marginLeft="14dp"
android:ems="10"
android:inputType="textPassword"
android:text="Password" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText"
android:layout_alignParentTop="true"
android:layout_marginTop="76dp"
android:text="Sign In"
android:textColor="@android:color/black"
android:textColorLink="@android:color/black"
android:textSize="28sp" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/S"
android:layout_alignParentLeft="true"
android:layout_marginLeft="18dp"
android:text="Password"
android:textColor="@android:color/black"
android:textSize="18sp" />

</RelativeLayout>

5.2.3 ListView Layout


Do you want to display a list in your app? Android has its solution by providing list view layout.
It is a layout which displays items in a vertical scroll-able list. Each item in the list is positioned
below to the previous item of the list. List items are stored in an array and inserted to the list
by using adapter which pulls items from array. List view is sub class of AdapterView. Custom
lists are very common in mobile application and list view provides a very easy way to create
custom lists. It is one of the most used layouts, for example when you want to display a group of
date, nothing could be more suitable than a list. Following figure shows how list view looks.
Attributes of List View
Here are some important XML attributes of list view.
android:divider, it is used as a draw able or color to draw between list items.
android:entries, it is used to reference an array resource to populate the list view.
android:headerDividersEnabled, used to draw divider after each header views.
android:footerDividersEanabled, used to draw divider before each footer views.

Methods of List View


List view has many public methods some of them are explained below.
 getAdapter( ): It returns adapter used in list view.
 addHeaderView( ): It is used to add a header view at the top of list.
 getAccessibilityClassName( ): It returns the class name of object.
 getDivider( ): returns the divider between each item of the list.
 getDividerHeight( ): returns divider height.
 isOpaque( ): Shows whether list is opaque or not.
 removeFooterView( View view): It is used to remove previously added footer view in
the list.
 removeHeaderView( View view): It is used to remove previously added header view in
the list.

Constructors of List View


 List view has four different public constructors as written below:
 ListView(Context context )
 ListView(Context context, AttributeSet attrs )
 ListView(Context context, AttributeSet attrs, int defStyleAttr )
 ListView(Context context,AttributeSet attrs,AttributeSet attrs,int defStyleRes )

Example of List View


Here is an example of using list view in Android. It shows list of languages in computer science.
Let’s start it by creating an activity, open activity _main.xml and paste this code.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout 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:orientation="vertical">

<ListView
android:id="@+id/mobile_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>

</LinearLayout>

open your MainActivity.java and use this code

package com.example.llistviewexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;

public class MainActivity extends Activity{

ListView lst;
String[] mobileArray =
{"Android","IPhone","WindowsMobile","Blackberry","WebOS","Ubuntu",
"Windows7","Max OS X"};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

lst = (ListView) findViewById(R.id.mobile_list);


final ArrayAdapter<String> myAdapter = new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,mobileArray);
lst.setAdapter(myAdapter);

lst.setOnItemClickListener(new AdapterView.OnItemClickListener(){

public void onItemClick(AdapterView<?> parent, View view, int


position,long id) {
String value=myAdapter.getItem(position);
Toast.makeText(getApplicationContext(),"You selected
"+value,Toast.LENGTH_SHORT).show();
}
});
}
}
5.2.4 GridView Layout

Grid view is a layout in android which lets you arrange components in a two-dimensional
scrollable grid. Components in a GirdView are not necessarily static, it can be stored in a
ListAdapter(Adapter is like a bridge between data and UI components). Following figure shows
an example of GridView in android.

Grid view is very common in applications like calculator, calendar and many others.

Attributes of Grid View


Following are some XML attributes of Android grid view layout.
android:gravity, represents gravity in each cell like center, bottom, top, left etc.
android:columnWidth, used to specify width of column for each cell.
android:horizontalSpacing, specify horizontal space between columns of grid.
android:verticalSpacing, used to specify vertical space between rows of grid.
android:numColumns, specify number of columns to show.

Methods of Grid View


Grid view has many methods to use, some of them are explained here
 getAccessibilityClassName(): return the class name of object.
 getAdapter(): return adapter associated with it.
 getColumnWidth(): return width of a column on grid.
 getGravity(): return gravity of grid component that is how they are aligned horizontally.
 getHorizontalSpacing(): return horizontal spacing between grid component.
 getNumColumns(): get number of columns in the grid.
 setAdapter( ListAdapter adapter): used to set the data behind grid view.
 setColumnWidth( int columnWidth): used to set column width.
 setGravity( int gravity): used to set gravity of grid’s component.
 setHorizontalSpacing( int horizontalSpacing): used to set horizontal spacing to place
item in grid.
 setVerticalSpacing( int verticalSpacing): used to set vertical spacing to place item on
grid.

Constructors of Grid View


Gird view has four different public constructors as defined below
 GridView( Content context)
 GridView( Content context, AttributeSet attrs)
 GridView( Content context, AttributeSet attrs, int defStyleAttr)
 GridView( Content context, AttributeSet attrs, int defStyleAttr, int defStyleRes)

Grid View Example


This example shows how to use GridView layout in Android. As mentioned earlier GridView
can be use directly or with the use of custom adapter. This example shows grid of small and
capital English alphabets.
Open Android Studio and start creating a new project. Create an activity and paste the following
code in main_Activity.xml.

<?xml version="1.0" encoding="utf-8"?>

<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridView1"
android:numColumns="auto_fit"
android:gravity="center"
android:columnWidth="80dp"
android:stretchMode="columnWidth"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</GridView>

Open mainActivity.java and paste this code

package com.example.gridviewexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;

public class MainActivity extends Activity {


GridView gridView;
static final String[] numbers = new String[] {
"A", "B", "C", "D", "E",
"F", "G", "H", "I", "J",
"K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z"};

public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

gridView = (GridView) findViewById(R.id.gridView1);

ArrayAdapter<String> adapter = new


ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, numbers);
gridView.setAdapter(adapter);

gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,int position, long id) {
Toast.makeText(getApplicationContext(),((TextView) v).getText(),
Toast.LENGTH_SHORT).show();
}
});

}
}

5.3 Explain the usage of User Interface Controls


5.3.1 TextView

In Android, TextView is a user interface control which is used to set and display the text to the
user based on our requirements. The TextView control will act as like label control and it won’t
allow users to edit the text.

In android, we can create a TextView control in two ways either in XML layout file or create it
in Activity file programmatically.

Create a TextView in Layout File


Following is the sample way to define TextView control in XML layout file in android
application.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="Welcome to TextView control"
android:textColor="#86AD33"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>

Create a TextView in Activity File


In android, we can create a TextView control programmatically in activity file based on our
requirements.
Following is the example of creating a TextView control dynamically in activity file.

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

LinearLayout lLayout = (LinearLayout) findViewById(R.id.linearlayout);


TextView tView = new TextView(this);
tView.setText("Welcome to UI controls");
lLayout.addView(tView);
}
}

Set the Text of Android TextView


In android, we can set the text of TextView control either while declaring it in Layout file or by
using setText() method in Activity file.
Following is the example to set the text of TextView control while declaring it in XML Layout
file.

<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=" Welcome to UI controls " />
If you observe above example we used android:text property to set required text for TextView
control in XML Layout file.

Following is another way to set the text of TextView control programmatically in activity file
using setText() method.
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText("Welcome to UI controls");

If you observe above code, we are getting the TextView control defined in XML layout file in
Activity file using id property and setting the text using setText() method.

Android TextView Attributes


Following are the some of commonly used attributes related to TextView control in android
applications.

Attribute Description

android: id It is used to uniquely identify the control


android:autoLink It will automatically found and convert urls and email addresses
as a clickable links.
android:hint It is used to display the hint text when text is empty
android:width It makes the TextView be exactly this many pixels wide.
android:height It makes the TextView be exactly this many pixels tall.
android:text It is used to display the text.
android:textColor It is used to change the color of text.
android:gravity It is used to specify how to align the text by the view's x and y
axis.
android:maxWidth It is used to make the TextView be at most this many pixels wide.
android:minWidth It is used to make the TextView be at least this many pixels wide.
android:textSize It is used to specify the size of text.
android:textStyle It is used to change the style (bold, italic, bolditalic) of text.
android:textAllCaps It is used to present the text in all CAPS
android:textColorHighlight It is used to change the color of text selection highlight.
android:textColorLink It is used to change the text color of links.
android:inputType It is used to specify the type of text being placed in a text fields.
android:fontFamily It is used to specify the fontFamily for the text.

Android TextView Example


Following is the example of using TextView control in android application.

Create a new android application using android studio and give names as TextViewExample.

Now open an activity_main.xml file from \res\layout path and write the code like as shown
below
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text=" Welcome to UI controls "
android:textColor="#86AD33"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:textAllCaps="true" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to UI controls"
android:textStyle="bold"
android:textColor="#fff"
android:background="#7F3AB5"
android:layout_marginBottom="15dp"/>
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="email|web"
android:text=" http://www.google.co.in" />
</LinearLayout>

MainActivity.java
package com.example.textviewexample;

import android.app.Activity;
import android.os.Bundle;
import android.widget.*;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView)findViewById(R.id.textView2);
tv.setText("Welcome to UI controls");
}
}

Output of Android TextView Example

5.3.2 Edit Text

In android, EditText is a user interface control which is used to allow the user to enter or modify
the text. While using EditText control in our android applications, we need to specify the type of
data the text field can accept using inputType attribute.

For example, if it accept plain text, then we need to specify the inputType as “text”. In case
if EditText field is for password, then we need to specify the inputType as “textPassword”.

In android, EditText control is an extended version of TextView control with an additional


features and it is used to allow users to enter input values.

In android, we can create EditText control in two ways either in XML layout file or create it
in Activity file programmatically.

Create a EditText in Layout File

Following is the sample way to define EditText control in XML layout file in android
application.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/txtSub"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Subject"
android:inputType="text"/>
</LinearLayout>
Create EditText Control in Activity File

In android, we can create EditText control programmatically in activity file to allow users to
enter text based on our requirements.

Following is the example of creating EditText control dynamically in activity file.

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearlayout);


EditText et = new EditText(this);
et.setHint("Subject");
linearLayout.addView(et);
}
}

Set the Text of Android EditText

In android, we can set the text of EditText control either while declaring it in Layout file or by
using setText() method in Activity file.

<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Welcome to EditText Control" />

If you observe above example we used android:text property to the set required text
for EditText control in XML Layout file.

Following is another way to set the text of EditText control programmatically in activity file
using setText() method.

EditText et = (EditText)findViewById(R.id.editText1);
et.setText("Welcome to EditText Control ");

Get Text of Android EditText


In android, we can get the text of EditText control by using getText() method in Activity file.

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText et = (EditText) findViewById(R.id.txtSub);
String name = et.getText().toString();
}
}

Android EditText Attributes


Following are the some of commonly used attributes related to EditText control in android
applications.

Attribute Description

android:id It is used to uniquely identify the control

It is used to specify how to align the text like left, right, center,
android:gravity top, etc.

android:text It is used to set the text.

android:hint It is used to display the hint text when text is empty

android:textColor It is used to change the color of text.

android:textColorHint It is used to change the text color of hint text.

android:textSize It is used to specify the size of text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:background It is used to set the background color for edit text control

android:width It makes the TextView be exactly this many pixels wide.

android:height It makes the TextView be exactly this many pixels tall.

It is used to make the TextView be at most this many pixels


android:maxWidth wide.

It is used to make the TextView be at least this many pixels


android:minWidth wide.

android:textAllCaps It is used to present the text in all CAPS


Attribute Description

android:textColorHighli
ght It is used to change the color of text selection highlight.

It is used to specify the type of text being placed in a text


android:inputType fields.

android:fontFamily It is used to specify the fontFamily for the text.

android:editable If we set false, EditText won't allow us to enter or modify text

Android EditText Control Example

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="40dp"
android:orientation="vertical" android:id="@+id/linearlayout" >
<EditText
android:id="@+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:ems="10"
android:hint="Name"
android:inputType="text"
android:selectAllOnFocus="true" />
<EditText
android:id="@+id/txtPwd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Password 0 to 9"
android:inputType="numberPassword" />
<EditText
android:id="@+id/txtEmai"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Email"
android:inputType="textEmailAddress" />
<EditText
android:id="@+id/txtDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Date"
android:inputType="date" />
<EditText
android:id="@+id/txtPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Phone Number"
android:inputType="phone"
android:textColorHint="#FE8DAB"/>
<Button
android:id="@+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="submit"
android:textSize="16sp"
android:textStyle="normal|bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/resultView"
android:layout_marginTop="25dp"
android:textSize="15sp"/>
</LinearLayout>

If you observe above code we created multiple EditText controls with different inputTypes,
such as password, email address, date, phone number, plain text.

MainActivity.java
package com.example.edittextexample;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {


Button btnSubmit;
EditText name, password, email, dob, phoneno;
TextView result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

name=(EditText)findViewById(R.id.txtName);
password = (EditText)findViewById(R.id.txtPwd);
email = (EditText)findViewById(R.id.txtEmai);
dob = (EditText)findViewById(R.id.txtDate);
phoneno= (EditText)findViewById(R.id.txtPhone);
btnSubmit = (Button)findViewById(R.id.btnSend);
result = (TextView)findViewById(R.id.resultView);

btnSubmit.setOnClickListener(new View.OnClickListener() {
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
public void onClick(View v) {
if (name.getText().toString().isEmpty()|| password.getText().toString().isEmpty()
|| email.getText().toString().isEmpty() || dob.getText().toString().isEmpty()
|| phoneno.getText().toString().isEmpty()) {
result.setText("Please Fill All the Details");
}
else {
result.setText("Name - " + name.getText().toString() + " \n" + "Password - "
+ password.getText().toString()+ " \n" + "E-Mail - " +
email.getText().toString() + " \n" + "DOB - " + dob.getText().toString() + "
\n" + "Contact - " + phoneno.getText().toString());
}
}
});
}
}

5.3.3 Button

In android, Button is a user interface control which is used to perform an action whenever the
user click or tap on it.

Generally, Buttons in android will contains a text or an icon or both and perform an action when
user touches it.

Following is the pictorial representation of using Buttons in android applications.

In android, we have different type of buttons available to use based on our requirements, those
are ImageButton, ToggleButton, RadioButton.

In android, we can create a Button control in two ways either in XML layout file or create it
in Activity file programmatically.
Create Button in XML Layout File

Following is the sample way to define Button control in XML layout file in android application.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/addBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add" />
</LinearLayout>

Create Button Control in Activity File


In android, we can create Button control programmatically in activity file based on our
requirements.

LinearLayout layout = (LinearLayout)findViewById(R.id.l_layout);


Button btn = new Button(this);
btn.setText("Test");
layout.addView(btn);

Android Handle Button Click Events


Generally, whenever the user clicks on a Button, the Button object will receives an on-click
event.

In android, we can define button click event in two ways either in XML layout file or create it
in Activity file programmatically.

Define Button Click Event in XML Layout File

We can define click event handler for button by adding android:onClick attribute to
the <Button> element in our XML layout file.

The value of android:onClick attribute must be the name of method which we need to call in
response to a click event and the Activity file which hosting XML layout must implement the
corresponding method.

Following is the example of defining a button click event using android:onClick attribute in
XML layout file.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/addBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:onClick="addOperation"/>
</LinearLayout>
In Activity that hosts our XML layout file, we need to implement click event method like as
shown below

/** Called when the user touches the button */


public void addOperation(View view) {
// Do something in response to button click
}

Define Button Click Event in Activity File

In android, we can define button click event programmatically in Activity file rather than XML
layout file.

To define button click programmatically, create View.OnClickListener object and assign it to


the button by calling setOnClickListener(View.OnClickListener) like as shown below.

Button btnAdd = (Button)findViewById(R.id.addBtn);


btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
}
});

Android Button Control Attributes

Attribute Description

android:id It is used to uniquely identify the control

android:gravity It is used to specify how to align the text like left, right, center,
top, etc.

android:text It is used to set the text.

android:textColor It is used to change the color of text.

android:textSize It is used to specify the size of text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:background It is used to set the background color for button control.

android:drawableBottom It’s a drawable to be drawn to the below of text.


Attribute Description

android:drawableRight It’s a drawable to be drawn to the right of text.

android:drawableLeft It’s a drawable to be drawn to the left of text.

Android Button Control Example

Following is the example of defining one Button and two EditText controls in LinearLayout to
get the data of EditText controls when click on Button in android application.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="150dp"
android:text="First Number" />
<EditText
android:id="@+id/firstNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<TextView
android:id="@+id/secTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Second Number"
android:layout_marginLeft="100dp" />
<EditText
android:id="@+id/secondNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<Button
android:id="@+id/addBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Add" />
</LinearLayout>
If you observe above code we created one Button, two TextView controls and
two EditText controls in XML Layout file.

MainActivity.java

package com.example.buttonexample;

import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText firstNum = (EditText)findViewById(R.id.firstNum);
final EditText secNum = (EditText)findViewById(R.id.secondNum);
Button btnAdd = (Button)findViewById(R.id.addBtn);
btnAdd.setOnClickListener(new View.OnClickListener() {
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
public void onClick(View v) {
if(firstNum.getText().toString().isEmpty() ||
secNum.getText().toString().isEmpty())
{
Toast.makeText(getApplicationContext(), "Please fill all the fields",
Toast.LENGTH_SHORT).show();
}
else {
int num1 = Integer.parseInt(firstNum.getText().toString());
int num2 = Integer.parseInt(secNum.getText().toString());
Toast.makeText(getApplicationContext(), "SUM = " + (num1 + num2),
Toast.LENGTH_SHORT).show();
}
}
});
}
}
5.3.4 Checkbox

In android, CheckBox is a two states button that can be either checked (ON) or unchecked
(OFF) and it will allow users to toggle between the two states (ON / OFF) based on the
requirements.

Generally, we can use multiple CheckBox controls in android application to allow users to select
one or more options from the set of values.

Following is the pictorial representation of using CheckBox control in android applications.

By default, the android CheckBox will be in OFF (Unchecked) state. We can change the default
state of CheckBox by using android:checked attribute.

In case, if we want to change the state of CheckBox to ON (Checked), then we need to


set android:checked = “true” in our XML layout file.

In android, we can create CheckBox control in two ways either in XML layout file or create it
in Activity file programmatically.

Create CheckBox in XML Layout File

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<CheckBox
android:id="@+id/chk1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Java" /> </RelativeLayout>
If you observe above code snippet, here we defined CheckBox control and setting CheckBox
state ON using android:checked attribute in xml layout file.

Create CheckBox Control in Activity File


In android, we can create CheckBox control programmatically in activity file based on our
requirements.

Following is the example of creating a CheckBox control dynamically in activity file.


LinearLayout layout = (LinearLayout)findViewById(R.id.l_layout);
CheckBox cb = new CheckBox(this);
cb.setText("Welcome to Checkbox Control");
cb.setChecked(true);
layout.addView(cb);

Define CheckBox Click Event in XML Layout File

We can define click event handler for button by adding android:onClick attribute to the
<CheckBox> element in our XML layout file.

The value of android:onClick attribute must be the name of method which we need to call in
response to a click event and the Activity file which hosting XML layout must implement the
corresponding method.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:id="@+id/chk1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Java"

android:onClick="onCheckBoxClick"/>
</LinearLayout>

In Activity that hosts our XML layout file, we need to implement click event method like as
shown below.
public void onCheckboxClicked(View view) {
// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.chk1:
if (checked)
// Do your coding
else
// Do your coding
break;
// Perform your logic
}
}

Define CheckBox Click Event in Activity File

In android, we can define CheckBox click event programmatically in Activity file rather than
XML layout file.

To define checkbox click event programmatically, create View.OnClickListener object and


assign it to the button by calling setOnClickListener(View.OnClickListener) like as shown
below.

CheckBox chk = (CheckBox) findViewById(R.id.chk1);


chk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean checked = ((CheckBox) v).isChecked();
// Check which checkbox was clicked
if (checked){
// Do your coding
}
else{
// Do your coding
}
}
});

Android CheckBox Control Attributes

Attribute Description

android:id It is used to uniquely identify the control

android:checked It is used to specify the current state of checkbox

android:gravity It is used to specify how to align the text like left, right, center, top, etc.

android:text It is used to set the text for checkbox.

android:textColor It is used to change the color of text.

android:textSize It is used to specify the size of text.


Attribute Description

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:background It is used to set the background color for checkbox control.

android:onClick It’s a name of the method to invoke when the checkbox clicked.

android:visibility It is used to control the visibility of control.

CheckBox Control Example

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<CheckBox
android:id="@+id/chkJava"
android:layout_width="73dp"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="150dp"
android:onClick="onCheckboxClicked"
android:text="Java" />

<CheckBox
android:id="@+id/chkPython"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Python"
android:onClick="onCheckboxClicked"/>
<CheckBox
android:id="@+id/chkAndroid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Android"
android:onClick="onCheckboxClicked"/>
<CheckBox
android:id="@+id/chkAngular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="AngularJS"
android:onClick="onCheckboxClicked"/>
</LinearLayout>

MainActivity.java

package com.example.checkboxexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.Toast;

public class MainActivity extends Activity {


CheckBox android, java, angular, python;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

android = (CheckBox)findViewById(R.id.chkAndroid);
angular = (CheckBox)findViewById(R.id.chkAngular);
java = (CheckBox)findViewById(R.id.chkJava);
python = (CheckBox)findViewById(R.id.chkPython);
}
public void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
String str="";
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.chkAndroid:
str = checked?"Android Selected":"Android Deselected";
break;
case R.id.chkAngular:
str = checked?"AngularJS Selected":"AngularJS Deselected";
break;
case R.id.chkJava:
str = checked?"Java Selected":"Java Deselected";
break;
case R.id.chkPython:
str = checked?"Python Selected":"Python Deselected";
break;
}
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}
}
5.3.5 Radio Button

In android, Radio Button is a two states button that can be either checked or unchecked and it’s
a same as CheckBox control, except that it will allow only one option to select from the group of
options.

The user can press or click on radio button to make it select. In android, CheckBox control allow
users to change the state of control either Checked or Unchecked but the radiobutton cannot be
unchecked once it is checked.

Generally, we can use RadioButton controls in android application to allow users to select only
one option from the set of values.

In android, we use radio buttons with in a RadioGroup to combine multiple radio buttons into
one group and it will make sure that user can select only one option from the group of multiple
options.

By default, the android RadioButton will be in OFF (Unchecked) state. We can change the
default state of RadioButton by using android:checked attribute.

In case, if we want to change the state of RadioButton to ON (Checked), then we need to


set android:checked = “true”in our XML layout file.

In android, we can create RadioButton control in two ways either in XML layout file or create it
in Activity file programmatically.
Create RadioButton in XML Layout File

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Java"
android:checked="true"/>
</RelativeLayout>

Create RadioButton Control in Activity File

LinearLayout layout = (LinearLayout)findViewById(R.id.l_layout);


RadioButton rd = new RadioButton(this);
rd.setText("Tutlane");
rd.setChecked(true);
layout.addView(rd);

Define RadioButton Click Event in XML Layout File

We can define click event handler for button by adding android:onClick attribute to
the <RadioButton> element in our XML layout file.

The value of android:onClick attribute must be the name of method which we need to call in
response to a click event and the Activity file which hosting XML layout must implement the
corresponding method.

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Java"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
</RelativeLayout>

In Activity that hosts our XML layout file, we need to implement click event method like as
shown below.

public void onRadioButtonClicked(View view) {


// Is the view now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which RadioButton was clicked
switch(view.getId()) {
case R.id.chk1:
if (checked)
// Do your coding
else
// Do your coding
break;
// Perform your logic
}
}

Define RadioButton Click Event in Activity File

In android, we can define RadioButton click event programmatically in Activity file rather than
XML layout file.

To define RadioButton click event programmatically, create View.OnClickListener object and


assign it to the button by calling setOnClickListener(View.OnClickListener) like as shown
below.

RadioButton rdb = (RadioButton) findViewById(R.id.radiobutton1);


rdb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean checked = ((RadioButton) v).isChecked();
// Check which radiobutton was pressed
if (checked){
// Do your coding
}
else{
// Do your coding
}
}
});

Android RadioButton Control Attributes

Attribute Description

android:id It is used to uniquely identify the control

android:checked It is used to specify the current state of radio button

android:gravity It is used to specify how to align the text like left, right, center, top, etc.

android:text It is used to set the text for radio button.

android:textColor It is used to change the color of text.

android:textSize It is used to specify the size of text.


Attribute Description

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:background It is used to set the background color for radio button control.

android:onClick It’s a name of the method to invoke when the radio button clicked.

android:visibility It is used to control the visibility of control.

Android RadioButton Control Example

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">

<RadioGroup
android:id="@+id/rdGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/txtView"
android:orientation="vertical" >
<RadioButton
android:id="@+id/rdbJava"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Java"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="@+id/rdbPython"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Python"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="@+id/rdbAndroid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Android"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="@+id/rdbAngular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="AngularJS"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
<TextView
android:id="@+id/txtView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="78dp"
android:text="Select Your Course"
android:textSize="18dp"
android:textStyle="bold" />

</RelativeLayout>

MainActivity.java
package com.example.radiobuttonexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.Toast;

public class MainActivity extends Activity {


RadioButton android, java, angular, python;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

android = (RadioButton)findViewById(R.id.rdbAndroid);
angular = (RadioButton)findViewById(R.id.rdbAngular);
java = (RadioButton)findViewById(R.id.rdbJava);
python = (RadioButton)findViewById(R.id.rdbPython);
}
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
String str="";
// Check which radio button was clicked
switch(view.getId()) {
case R.id.rdbAndroid:
if(checked)
str = "Android Selected";
break;
case R.id.rdbAngular:
if(checked)
str = "AngularJS Selected";
break;
case R.id.rdbJava:
if(checked)
str = "Java Selected";
break;
case R.id.rdbPython:
if(checked)
str = "Python Selected";
break;
}
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}
}

5.3.6 Toggle button

In android, Toggle Button is a user interface control which is used to display ON (Checked)
or OFF (Unchecked) states as a button with a light indicator.

The ToggleButton is useful for the users to change the settings between two states
either ON or OFF. We can add a ToggleButton to our application layout by
using ToggleButton object.

Following is the pictorial representation of using ToggleButton in android applications.

By default, the android ToggleButton will be in OFF (Unchecked) state. We can change the
default state of ToggleButton by using android:checked attribute.

In case, if we want to change the state of ToggleButton to ON (Checked), then we need to


set android:checked = “true”in our XML layout file.
In android, we can create ToggleButton control in two ways either in XML layout file or create
it in Activity file programmatically.

Create ToggleButton in XML Layout File

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ToggleButton
android:id="@+id/toggle1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="120dp"
android:checked="true"
android:textOff="OFF"
android:textOn="ON"/>
</RelativeLayout>

Create ToggleButton Control in Activity File

RelativeLayout layout = (RelativeLayout)findViewById(R.id.r_layout);


ToggleButton tb = new ToggleButton(this);
tb.setTextOff("OFF");
tb.setTextOn("ON");
tb.setChecked(true);
layout.addView(tb);

Handle Android ToggleButton Click Events

Generally, whenever the user clicks on ToggleButton, we can detect whether ToggleButton is
in ON or OFF state and we can handle ToggleButton click event in activity file
using setOnCheckedChangeListener like as shown below.

ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);


toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListen
er() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled
} else {
// The toggle is disabled
}
}
});

Android ToggleButton Control Attributes


Attribute Description

android:id It is used to uniquely identify the control

android:checked It is used to specify the current state of toggle button

android:gravity It is used to specify how to align the text like left, right, center, top,
etc.

android:text It is used to set the text.

android:textOn It is used to set the text when toggle button is in ON / Checked


state.

android:textOff It is used to set the text when toggle button is in OFF / Unchecked
state.

android:textColor It is used to change the color of text.

android:textSize It is used to specify the size of text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:background It is used to set the background color for toggle button control.

android:padding It is used to set the padding from left, right, top and bottom.

android:drawableBottom It’s a drawable to be drawn to the below of text.

android:drawableRight It’s a drawable to be drawn to the right of text.

android:drawableLeft It’s a drawable to be drawn to the left of text.

Android ToggleButton Control Example

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">

<Button
android:id="@+id/getBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Submit" />
<ToggleButton
android:id="@+id/toggle1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/getBtn"
android:layout_alignRight="@+id/getBtn"
android:layout_marginBottom="38dp"
android:layout_marginRight="39dp"
android:checked="true"
android:textOff="OFF"
android:textOn="ON" />
<ToggleButton
android:id="@+id/toggle2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/toggle1"
android:layout_alignBottom="@+id/toggle1"
android:layout_alignLeft="@+id/getBtn"
android:layout_marginLeft="60dp"
android:textOff="OFF"
android:textOn="ON" />

</RelativeLayout>

MainActivity.java

package com.example.togglebuttonexample;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends Activity {


protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final ToggleButton tb1 = (ToggleButton)findViewById(R.id.toggle1);


final ToggleButton tb2 = (ToggleButton)findViewById(R.id.toggle2);
Button btnGet = (Button)findViewById(R.id.getBtn);

btnGet.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Toggle Button1 - " +
tb1.getText().toString() + " \n" + "Toggle Button2 - " +
tb2.getText().toString(),Toast.LENGTH_SHORT).show();
}
});
}
}

5.3.7 Spinner

In android, Spinner is a view which allow a user to select one value from the list of values. The
spinner in android will behave same like dropdown list in other programming languages.

Generally, the android spinners will provide a quick way to select one item from the list of
values and it will show a dropdown menu with a list of all values when we click or tap on it.

By default, the android spinner will show its currently selected value and by using Adapter we
can bind the items to spinner object.

We can populate our Spinner control with list of choices by defining an ArrayAdapter in
our Activity file.

Generally, the Adapter pulls data from the sources such as an array or database and converts
each item into a result view and that’s placed into the list.

Android Adapter

In android, Adapter will act as an intermediate between the data sources and adapter views such
as ListView, Gridview to fill the data into adapter views. The adapter will hold the data and
iterates through the items in data set and generate the views for each item in the list.

Generally, in android we have different types of adapters available to fetch the data from
different data sources to fill the data into adapter views, those are

Adapter Description

ArrayAdapter It will expects an Array or List as input.

CurosrAdapter It will accepts an instance of cursor as an input.

SimpleAdapter It will accepts a static data defined in the resources.


Adapter Description

BaseAdapter It is a generic implementation for all three adapter types and it can be used for
ListView, Gridview or Spinners based on our requirements

Create Android Spinner in XML Layout File

In android, we can create Spinner in XML layout file using <Spinner> element with different
attributes like as shown below.

<Spinner android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

Populate Android Spinner with Values

To populate spinner with list of values, we need to specify spinner adapter, such as
an ArrayAdapter in activity file like as shown below.

String[] languages = { "C", "C++", "Java", "C#.NET"};


Spinner spin = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.si
mple_spinner_item, languages);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
;
spin.setAdapter(adapter);

Android Spinner Example

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:id="@+id/txtVw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="150dp"
android:text="Select User:"
android:textStyle="bold"
android:textSize="15dp" />
<Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/txtVw"
android:layout_toRightOf="@+id/txtVw" />
</RelativeLayout>

MainActivity.java

package com.example.spinnerexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity implements


AdapterView.OnItemSelectedListener
{
String[] languages = { "C", "C++", "Java", "C#.NET"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Spinner spin = (Spinner) findViewById(R.id.spinner1);


ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, languages);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
;
spin.setAdapter(adapter);
spin.setOnItemSelectedListener(this);
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {
Toast.makeText(getApplicationContext(), "Selected Laungauge:
"+languages[position] ,Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub

}
}
5.3.8 Date picker

In android, DatePicker is a control which will allow users to select the date by day, month and
year in our application user interface.

If we use DatePicker in our application, it will ensure that the users will select a valid date.

Following is the pictorial representation of using a datepicker control in android applications.

Generally, in android DatePicker available in two modes, one is to show the complete calendar
and another one is to show the dates in spinner view.

Create Android DatePicker in XML Layout File

<DatePicker android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

In anroid, the DatePicker supports a two types of modes, those are Calendar and Spinner to
show the date details in our application.

Android DatePicker with Calendar Mode


We can define android DatePicker to show only calendar view by using
DatePicker android:datePickerMode attribute.

<DatePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="calendar"/>

Android DatePicker with Spinner Mode

If we want to show the DatePicker in spinner format like showing day, month and year
separately to select the date, then by using DatePicker android:datePickerMode attribute we can
achieve this.

<DatePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner"/>

If you observe above result we got the DatePicker in both Spinner and Calendar modes to select
the date.

To get only spinner mode date selection, then we need to


set android:calendarViewShown="false" attribute in DatePicker control like as shown below.
<DatePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner"
android:calendarViewShown="false"/>

Android DatePicker Control Attributes

Attribute Description

android:id It is used to uniquely identify the control

android:datePickerMode It is used to specify datepicker mode either spinner or calendar

android:background It is used to set the background color for date picker.

android:padding It is used to set the padding for left, right, top or bottom of date
picker.

Android DatePicker Example

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<DatePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/datePicker1"
android:layout_marginLeft="100dp"
android:text="Get Date" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_marginLeft="100dp"
android:layout_marginTop="10dp"
android:textStyle="bold"
android:textSize="18dp"/>
</RelativeLayout>

MainActivity.java

package com.example.datepickerexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class MainActivity extends Activity {

DatePicker picker;
Button btnGet;
TextView tvw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

tvw=(TextView)findViewById(R.id.textView1);
picker=(DatePicker)findViewById(R.id.datePicker1);
btnGet=(Button)findViewById(R.id.button1);

btnGet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tvw.setText("Selected Date: "+ picker.getDayOfMonth()+"/"+
(picker.getMonth() + 1)+"/"+picker.getYear());
}
});
}
}
5.3.9 Time picker

In android, TimePicker is a widget for selecting the time of day, in either 24-hour or AM/PM
mode.

If we use TimePicker in our application, it will ensure that the users will select a valid time for
the day.

Following is the pictorial representation of using a timepicker control in android applications.

Generally, in android TimePicker available in two modes, one is to show the time in clock mode
and another one is to show the time in spinner mode.

Create Android DatePicker in XML Layout File

<TimePicker android:id="@+id/timePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

In anroid, the TimePicker supports two types of modes; those are Clock and Spinner to show the
date details in our application.

Android TimePicker with Clock Mode

We can define android TimePicker to show time in clock format by using


TimePicker android:timePickerMode attribute.

Following is the example of showing the TimePicker in Clock mode.


<TimePicker android:id="@+id/timePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:timePickerMode="clock" />

Android TimePicker with Spinner Mode

If we want to show the TimePicker in spinner format like showing hours and minutes separately
to select the time, then by using TimePicker android:timePickerMode attribute we can achieve
this.
<TimePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:timePickerMode="spinner"/>

We can change the TimePicker in spinner mode to AM / PM format instead of 24 Hours format
by using setIs24HourView(true) method in Activity file like as shown below.

TimePicker picker = (TimePicker)findViewById(R.id.timePicker1);


picker.setIs24HourView(true);

Android TimePicker Control Attributes


Attribute Description

android:id It is used to uniquely identify the control

android:timePickerMode It is used to specify timepicker mode, either spinner or clock

android:background It is used to set the background color for date picker.

android:padding It is used to set the padding for left, right, top or bottom of date
picker.

Android TimePicker Example

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TimePicker
android:id="@+id/timePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/timePicker1"
android:layout_marginTop="10dp"
android:layout_marginLeft="160dp"
android:text="Get Time" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_marginLeft="120dp"
android:layout_marginTop="10dp"
android:textStyle="bold"
android:textSize="18dp"/>
</RelativeLayout>

MainActivity.java

package com.example.timepickerexample;

import android.os.Build;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;

public class MainActivity extends Activity {


TimePicker picker;
Button btnGet;
TextView tvw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvw=(TextView)findViewById(R.id.textView1);
picker=(TimePicker)findViewById(R.id.timePicker1);
picker.setIs24HourView(true);
btnGet=(Button)findViewById(R.id.button1);
btnGet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int hour, minute;
String am_pm;
if (Build.VERSION.SDK_INT >= 23 ){
hour = picker.getCurrentHour();
minute = picker.getCurrentMinute();
}
else{
hour = picker.getCurrentHour();
minute = picker.getCurrentMinute();
}
if(hour > 12) {
am_pm = "PM";
hour = hour - 12;
}
else
{
am_pm="AM";
}
tvw.setText("Selected Date: "+ hour +":"+ minute+" "+am_pm);
}
});
}
}
5.4 Develop an Android application that switches between Activities
In Android user interface is displayed through an activity. In Android app development you
might face situations where you need to switch between one Activity (Screen/View) to another.
Here we will be discussing about switching between one Activity to another and sending data
between activities.
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"
tools:context="${relativePackage}.${activityClass}" >

<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="52dp"
android:text="Click Me"
android:textColor="#FF00FF"
android:textSize="20sp" />

</RelativeLayout>

MainActivity.java

package com.example.explicitintentexample;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b=(Button) findViewById(R.id.btn);
b.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"Go to Next
Activity",Toast.LENGTH_LONG).show();
Intent i=new Intent(MainActivity.this,NextActivity.class);
startActivity(i);
}

});
}
}

activity_next.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/textView1"
android:layout_width="305dp"
android:layout_height="wrap_content"
android:layout_weight="0.03"
android:text="I am in Next Activity"
android:textSize="30sp" />

</LinearLayout>

NextActivity.java

package com.example.explicitintentexample;

import android.app.Activity;
import android.os.Bundle;

public class NextActivity extends Activity


{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
}
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.explicitintentexample"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NextActivity"/>
</application>

</manifest>

5.5 Develop simple Android applications using UI controls


Android Login and Registration Screens Example
To allow only registered users to our android application, we need to implement login and
registration screens to ask the users to register first, then login to the application to get an access
for the content in application.
Now we will see how to implement login and registration screens using material design in
android application like as shown following.
Following is the example of creating the login and registration screens in android application to
allow only valid users based on our requirements.

Create a new android application using android studio and give names as LoginExample.

Once we create an application, open activity_main.xml file from \res\layout folder path and
write the code like as shown below.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/loginscrn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="80dp"
android:text="Login"
android:textSize="25dp"
android:textStyle="bold"
android:layout_gravity="center"/>
<TextView
android:id="@+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="20dp"
android:text="Email"/>
<EditText
android:id="@+id/txtEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10"/>
<TextView
android:id="@+id/secTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:layout_marginLeft="100dp" />
<EditText
android:id="@+id/txtPwd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:inputType="textPassword"
android:ems="10" />
<Button
android:id="@+id/btnLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Login" />
<TextView android:id="@+id/lnkRegister"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:text="New to Tutlane? Register here"
android:gravity="center"
android:textSize="20dp"
android:textColor="#3F51B5"/>
</LinearLayout>

Now we will create another layout resource file registration.xml in \res\layout path to allow
new users to register in our application for that right click on your layout folder à Go
to New a select Layout Resource File and give name as registration.xml.

Once we create a new layout resource file registration.xml, open it and write the code like as
shown below

registration.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/loginscrn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="80dp"
android:text="Registration"
android:textSize="25dp"
android:textStyle="bold"
android:layout_gravity="center"/>
<TextView
android:id="@+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="20dp"
android:text="Full Name"/>
<EditText
android:id="@+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10"/>
<TextView
android:id="@+id/secTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email"
android:layout_marginLeft="100dp" />
<EditText
android:id="@+id/txtEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<TextView
android:id="@+id/thirdTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:layout_marginLeft="100dp" />
<EditText
android:id="@+id/txtPwd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:inputType="textPassword"
android:ems="10" />
<Button
android:id="@+id/btnLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Login" />
<TextView android:id="@+id/lnkLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:text="Already Registered? Login here"
android:gravity="center"
android:textSize="20dp"
android:textColor="#3F51B5"
android:onClick="test"/>
</LinearLayout>

Now open your main activity file MainActivity.java

MainActivity.java

package com.loginexample;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
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);
TextView register = (TextView)findViewById(R.id.lnkRegister);
register.setMovementMethod(LinkMovementMethod.getInstance());
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, RegistrationActivity.class);
startActivity(intent);
}
});
}
}
If you observe above code, whenever the user click on register link, we are redirecting the user
from login screen to registration screen using “RegistrationActivity” for that create
another activity file RegistrationActivity.java.
Now right click on your application folder à Go to New a select Java Class and give name
as RegistrationActivity.java.

Once we create a new activity file RegistrationActivity.java, open it and write the code like as
shown below

RegistrationActivity.java
package com.loginexample;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.TextView;

public class RegistrationActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registration);
TextView login = (TextView)findViewById(R.id.lnkLogin);
login.setMovementMethod(LinkMovementMethod.getInstance());
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
}

Now we need to add this newly created activity in AndroidManifest.xml file in like as shown
below.

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutlane.loginexample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".RegistrationActivity" android:label="Registration"> </activity
>
</application>
</manifest>
If you observe above example, we created login and registration screens and added all the
activities in AndroidManifest.xml file.

S-ar putea să vă placă și