Documente Academic
Documente Profesional
Documente Cultură
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.
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.
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.
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;
@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();
}
}
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.
Other than these attributes, linear layout has many different constructors.
</LinearLayout>
Here is another example which shows horizontal linear layout. Below is the code for
activity_linear_horizontal.xml
<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>
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,
<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>
<ListView
android:id="@+id/mobile_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
package com.example.llistviewexample;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
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.setOnItemClickListener(new AdapterView.OnItemClickListener(){
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.
<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>
package com.example.gridviewexample;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
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();
}
});
}
}
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.
<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.
Attribute Description
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.*;
@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");
}
}
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, we can create EditText control in two ways either in XML layout file or create it
in Activity file programmatically.
Following is the sample way to define EditText control in XML layout file in android
application.
In android, we can create EditText control programmatically in activity file to allow users to
enter text based on our requirements.
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 ");
Attribute Description
It is used to specify how to align the text like left, right, center,
android:gravity top, etc.
android:background It is used to set the background color for edit text control
android:textColorHighli
ght It is used to change the color of text selection highlight.
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;
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.
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>
In android, we can define button click event in two ways either in XML layout file or create it
in Activity file programmatically.
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.
In android, we can define button click event programmatically in Activity file rather than XML
layout file.
Attribute Description
android:gravity It is used to specify how to align the text like left, right, center,
top, etc.
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
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;
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.
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 android, we can create CheckBox control in two ways either in XML layout file or create it
in Activity file programmatically.
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.
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
}
}
In android, we can define CheckBox click event programmatically in Activity file rather than
XML layout file.
Attribute Description
android:gravity It is used to specify how to align the text like left, right, center, top, etc.
android:onClick It’s a name of the method to invoke when the checkbox clicked.
activity_main.xml
<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;
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 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
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.
In Activity that hosts our XML layout file, we need to implement click event method like as
shown below.
In android, we can define RadioButton click event programmatically in Activity file rather than
XML layout file.
Attribute Description
android:gravity It is used to specify how to align the text like left, right, center, top, etc.
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.
activity_main.xml
<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;
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();
}
}
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.
By default, the android ToggleButton will be in OFF (Unchecked) state. We can change the
default state of ToggleButton by using android:checked attribute.
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.
android:gravity It is used to specify how to align the text like left, right, center, top,
etc.
android:textOff It is used to set the text when toggle button is in OFF / Unchecked
state.
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.
activity_main.xml
<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;
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
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
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"/>
To populate spinner with list of values, we need to specify spinner adapter, such as
an ArrayAdapter in activity file like as shown below.
activity_main.xml
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;
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.
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.
<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.
<DatePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="calendar"/>
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.
Attribute Description
android:padding It is used to set the padding for left, right, top or bottom of date
picker.
activity_main.xml
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;
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.
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.
<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.
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.
android:padding It is used to set the padding for left, right, top or bottom of date
picker.
activity_main.xml
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;
<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
<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;
AndroidManifest.xml
<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>
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
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;
@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;
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.