0% found this document useful (0 votes)
16 views104 pages

Unit Iv

This document provides an overview of designing user interfaces in Android, focusing on TextView, EditText, and AutoCompleteTextView components. It details important attributes for each component, along with examples of how to implement them in an Android application using Android Studio. Additionally, it includes code snippets for creating a basic application that utilizes these UI elements and their attributes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views104 pages

Unit Iv

This document provides an overview of designing user interfaces in Android, focusing on TextView, EditText, and AutoCompleteTextView components. It details important attributes for each component, along with examples of how to implement them in an Android application using Android Studio. Additionally, it includes code snippets for creating a basic application that utilizes these UI elements and their attributes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 104

UNIT IV: Designing User Interface With View

4.1.1 TextView:
A TextView displays text to the user and optionally allows them to edit it. A TextView
is a complete text editor, however the basic class is configured to not allow editing.

4.1.1(A) TextView Attributes:


Following are the important attributes related to TextView control. You can check
Android official documentation for complete list of attributes and related methods
which you can use to change these attributes are run time.

Sr.No Attribute & Description


.

1 android:id
This is the ID which uniquely identifies the control.

2 android:capitalize
If set, specifies that this TextView has a textual input method and should
automatically capitalize what the user types.

 Don't automatically capitalize anything - 0


 Capitalize the first word of each sentence - 1
 Capitalize the first letter of every word - 2
 Capitalize every character - 3

3 android:cursorVisible
Makes the cursor visible (the default) or invisible. Default is false.

4 android:editable
If set to true, specifies that this TextView has an input method.

5 android:fontFamily
Font family (named by string) for the text.

6 android:gravity
Specifies how to align the text by the view's x- and/or y-axis when the text
is smaller than the view.

7 android:hint
Hint text to display when the text is empty.

8 android:inputType
The type of data being placed in a text field. Phone, Date, Time, Number,
Password etc.

9 android:maxHeight
Makes the TextView be at most this many pixels tall.

10 android:maxWidth
Makes the TextView be at most this many pixels wide.

11 android:minHeight
Makes the TextView be at least this many pixels tall.

12 android:minWidth
Makes the TextView be at least this many pixels wide.

13 android:password
Whether the characters of the field are displayed as password dots instead
of themselves. Possible value either "true" or "false".

14 android:phoneNumber
If set, specifies that this TextView has a phone number input method.
Possible value either "true" or "false".

15 android:text
Text to display.

16 android:textAllCaps
Present the text in ALL CAPS. Possible value either "true" or "false".
17 android:textColor
Text color. May be a color value, in the form of "#rgb", "#argb", "#rrggbb",
or "#aarrggbb".

18 android:textColorHighlight
Color of the text selection highlight.

19 android:textColorHint
Color of the hint text. May be a color value, in the form of "#rgb", "#argb",
"#rrggbb", or "#aarrggbb".

20 android:textIsSelectable
Indicates that the content of a non-editable text can be selected. Possible
value either "true" or "false".

21 android:textSize
Size of the text. Recommended dimension type for text is "sp" for scaled-
pixels (example: 15sp).

22 android:textStyle
Style (bold, italic, bolditalic) for the text. You can use or more of the
following values separated by '|'.

 normal - 0
 bold - 1
 italic - 2

23 android:typeface
Typeface (normal, sans, serif, monospace) for the text. You can use or
more of the following values separated by '|'.

 normal - 0
 sans - 1
 serif - 2
 monospace - 3
Example
This example will take you through simple steps to show how to create your
own Android application using Linear Layout and TextView.

Step Description

1 You will use Android studio to create an Android application and name it
as demo under a package com.example.demo as explained in the Hello
World Example chapter.

2 Modify src/MainActivity.java file to add necessary code .

3 Modify the default content of res/layout/activity_main.xml file to include


Android UI control.

4 No need to change default string constants at string.xml file. Android


studio takes care of default string constants.

5 Run the application to launch Android emulator and verify the result of the
changes done in the application.

Following is the content of the modified main activity


file src/com.example.demo/MainActivity.java. This file can include each of
the fundamental lifecycle methods.
package com.example.demo;

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

public class MainActivity extends Activity {


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

//--- text view---


TextView txtView =(TextView)findViewById(R.id.text_id);
}
}
Following will be the content of res/layout/activity_main.xml file −
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:id="@+id/text_id"
android:layout_width="300dp"
android:layout_height="200dp"
android:capitalize="characters"
android:text="hello_world"
android:textColor="@android:color/holo_blue_dark"

android:textColorHighlight="@android:color/primary_text_dark"
android:layout_centerVertical="true"
android:layout_alignParentEnd="true"
android:textSize="50dp"/>

</RelativeLayout>
Following will be the content of res/values/strings.xml to define two new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">demo</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.demo" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.demo.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>

</application>
</manifest>
Let's try to run your demo application. I assume you had created
your AVD while doing environment setup. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Android studio installs the app on your AVD and starts it and if everything is
fine with your setup and application, it will display following Emulator window −

4.1.2 EditText:
A EditText is an overlay over TextView that configures itself to be editable. It is
the predefined subclass of TextView that includes rich editing capabilities.
Styles of edit text

4.1.2(A) EditText Attributes:


Following are the important attributes related to EditText control. You can
check Android official documentation for complete list of attributes and related
methods which you can use to change these attributes are run time.
Inherited from android.widget.TextView Class −

Sr.No Attribute & Description

1 android:autoText
If set, specifies that this TextView has a textual input method and
automatically corrects some common spelling errors.

2 android:drawableBottom
This is the drawable to be drawn below the text.

3 android:drawableRight
This is the drawable to be drawn to the right of the text.

4 android:editable
If set, specifies that this TextView has an input method.

5 android:text
This is the Text to display.
Inherited from android.view.View Class −
Sr.N Attribute & Description
o

1 android:background
This is a drawable to use as the background.

2 android:contentDescription
This defines text that briefly describes content of the view.

3 android:id
This supplies an identifier name for this view.

4 android:onClick
This is the name of the method in this View's context to invoke when the view
is clicked.

5 android:visibility

This controls the initial visibility of the view.

Example
This example will take you through simple steps to show how to create your own
Android application using Linear Layout and EditText.

Step Description

1 You will use Android studio IDE to create an Android application and name it
as demo under a package com.example.demo as explained in the Hello World
Example chapter.

2 Modify src/MainActivity.java file to add a click event.


3 Modify the default content of res/layout/activity_main.xml file to include Android
UI control.

4 Define required necessary string constants in res/values/strings.xml file

5 Run the application to launch Android emulator and verify the result of the
changes done in the application.

Following is the content of the modified main activity


file src/com.example.demo/MainActivity.java. This file can include each of
the fundamental lifecycle methods.
package com.example.demo;

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

import android.view.View;
import android.view.View.OnClickListener;

import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {


EditText eText;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eText = (EditText) findViewById(R.id.edittext);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String str = eText.getText().toString();
Toast msg =
Toast.makeText(getBaseContext(),str,Toast.LENGTH_LONG);
msg.show();
}
});
}
}
Following will be the content of res/layout/activity_main.xml file −
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="14dp"
android:layout_marginTop="18dp"
android:text="@string/example_edittext" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="130dp"
android:text="@string/show_the_text" />
<EditText
android:id="@+id/edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button"
android:layout_below="@+id/textView1"
android:layout_marginTop="61dp"
android:ems="10"
android:text="@string/enter_text"
android:inputType="text" />

</RelativeLayout>
Following will be the content of res/values/strings.xml to define these new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">demo</string>
<string name="example_edittext">Example showing
EditText</string>
<string name="show_the_text">Show the Text</string>
<string name="enter_text">text changes</string>
</resources>
Following is the default content of AndroidManifest.xml –

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.demo" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.demo.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>
</application>
</manifest>
Let's try to run your demo application. I assume you had created
your AVD while doing environment setup. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Android Studio installs the app on your AVD and starts it and if everything is
fine with your setup and application, it will display following Emulator window −
4.1.3 AutoCompleteTextView:
An AutoCompleteTextView is a view that is similar to EditText, except that it
shows a list of completion suggestions automatically while the user is typing.
The list of suggestions is displayed in drop down menu. The user can choose
an item from there to replace the content of edit box with.

4.1.3(A) AutoCompleteTextView Attributes:


Following are the important attributes related to AutoCompleteTextView
control. You can check Android official documentation for complete list of
attributes and related methods which you can use to change these attributes
are run time.

Sr.No Attribute & Description

1 android:completionHint
This defines the hint displayed in the drop down menu.

android:completionHintView
2
This defines the hint view displayed in the drop down menu.

android:completionThreshold
3 This defines the number of characters that the user must type before
completion suggestions are displayed in a drop down menu.
android:dropDownAnchor
4
This is the View to anchor the auto-complete dropdown to.

android:dropDownHeight
5
This specifies the basic height of the dropdown.

android:dropDownHorizontalOffset
6 The amount of pixels by which the drop down should be offset
horizontally.

android:dropDownSelector
7
This is the selector in a drop down list.

android:dropDownVerticalOffset
8
The amount of pixels by which the drop down should be offset vertically.

android:dropDownWidth
9
This specifies the basic width of the dropdown.

android:popupBackground
10
This sets the background.

Example
This example will take you through simple steps to show how to create your
own Android application using Linear Layout and AutoCompleteTextView.

Ste Description
p

1 You will use Android Studio IDE to create an Android application and name
it as GUIDemo3 under a package com.example.guidemo3 as explained in
the Hello World Example chapter.

2 Modify src/MainActivity.java file to add a click event.

3 Modify the default content of res/layout/activity_main.xml file to include


Android UI control.

4 Define necessary constants in res/values/strings.xml file

5 Run the application to launch Android emulator and verify the result of the
changes done in the application.

Following is the content of the modified main activity


file src/com.example.guidemo3/MainActivity.java. This file can include each
of the fundamental lifecycle methods.
package com.example.guidemo3;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

public class MainActivity extends Activity {


AutoCompleteTextView autocomplete;

String[] arr = { "Paries,France", "PA,United


States","Parana,Brazil",
"Padua,Italy", "Pasadena,CA,United States"};

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

autocomplete = (AutoCompleteTextView)
findViewById(R.id.autoCompleteTextView1);

ArrayAdapter<String> adapter = new ArrayAdapter<String>


(this,android.R.layout.select_dialog_item, arr);

autocomplete.setThreshold(2);
autocomplete.setAdapter(adapter);
}
}
Following will be the content of res/layout/activity_main.xml file −
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:text="@string/example_autocompletetextview" />

<AutoCompleteTextView
android:id="@+id/autoCompleteTextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"
android:layout_below="@+id/textView2"
android:layout_marginTop="54dp"
android:ems="10" />

</RelativeLayout>
Following will be the content of res/values/strings.xml to define these new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">GUIDemo3</string>
<string name="example_autocompletetextview">Example
showing AutoCompleteTextView</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.guidemo3" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.guidemo3.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>

</application>
</manifest>
Let's try to run your GUIDemo3 application. I assume you had created
your AVD while doing environment setup. To run the app from Android Studio,
open one of your project's activity files and click Run icon from the toolbar.
Android Studio installs the app on your AVD and starts it and if everything is
fine with your setup and application, it will display following Emulator window −
The following screen will appear after "pa" will be typed in
AutoCompleteTextView −
4.1.4 Button:
A Button is a Push-button which can be pressed, or clicked, by the user to
perform an action.
4.1.4(A) Button Attributes:
Following are the important attributes related to Button control. You can check
Android official documentation for complete list of attributes and related
methods which you can use to change these attributes are run time.
Inherited from android.widget.TextView Class −

Sr.No Attribute & Description

1 android:autoText
If set, specifies that this TextView has a textual input method and
automatically corrects some common spelling errors.

2 android:drawableBottom
This is the drawable to be drawn below the text.

3 android:drawableRight
This is the drawable to be drawn to the right of the text.

4 android:editable
If set, specifies that this TextView has an input method.
5 android:text
This is the Text to display.

Inherited from android.view.View Class −

Attribute Description

1 android:background
This is a drawable to use as the background.

2 android:contentDescription
This defines text that briefly describes content of the view.

3 android:id
This supplies an identifier name for this view.

4 android:onClick
This is the name of the method in this View's context to invoke
when the view is clicked.

5 android:visibility
This controls the initial visibility of the view.

Example
This example will take you through simple steps to show how to create your
own Android application using Linear Layout and Button.

Step Description

1 You will use Android studio IDE to create an Android application and name it
as myapplication under a package com.example.saira_000.myapplication as
explained in the Hello World Example chapter.

2 Modify src/MainActivity.java file to add a click event.

Modify the default content of res/layout/activity_main.xml file to include Android


3
UI control.

No need to declare default string constants at string.xml, Android studio takes


4
care of default string constants.

Run the application to launch Android emulator and verify the result of the
5
changes done in the application.

Following is the content of the modified main activity


file src/MainActivity.java. This file can include each of the fundamental
lifecycle methods.
package com.example.saira_000.myapplication;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {


Button b1,b2,b3;

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

b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"YOUR
MESSAGE",Toast.LENGTH_LONG).show();
}
});
}
}
Following will be the content of res/layout/activity_main.xml file −
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button Control"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true" />

<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/imageButton"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:id="@+id/button"
android:layout_alignTop="@+id/editText"
android:layout_alignLeft="@+id/textView1"
android:layout_alignStart="@+id/textView1"
android:layout_alignRight="@+id/editText"
android:layout_alignEnd="@+id/editText" />

</RelativeLayout>
Following will be the content of res/values/strings.xml to define these new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">myapplication</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.saira_000.myapplication" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.guidemo4.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>

</application>
</manifest>
Let's try to run your GUIDemo4 application. I assume you had created
your AVD while doing environment setup. To run the app from Android Studio,
open one of your project's activity files and click Run icon from the
toolbar.Android Studio installs the app on your AVD and starts it and if
everything is fine with your setup and application, it will display following
Emulator window −

The following screen will appear by clicking on Button −


4.1.5 Image Button:
An ImageButton is an AbsoluteLayout which enables you to specify the exact
location of its children. This shows a button with an image (instead of text) that
can be pressed or clicked by the user.

Androi
d button style set

4.1.5(A) ImageButton Attributes:


Following are the important attributes related to ImageButton control. You can
check Android official documentation for complete list of attributes and related
methods which you can use to change these attributes are run time.
Inherited from android.widget.ImageView Class −

Sr.N Attribute & Description


o

android:adjustViewBounds
1
Set this to true if you want the ImageView to adjust its bounds to preserve the
aspect ratio of its drawable.

2 android:baseline
This is the offset of the baseline within this view.

3 android:baselineAlignBottom
If true, the image view will be baseline aligned with based on its bottom edge.

4 android:cropToPadding
If true, the image will be cropped to fit within its padding.

5 android:src
This sets a drawable as the content of this ImageView.

Inherited from android.view.View Class –

Sr.N Attribute & Description


o

1 android:background
This is a drawable to use as the background.
2 android:contentDescription
This defines text that briefly describes content of the view.

3 android:id
This supplies an identifier name for this view

4 android:onClick
This is the name of the method in this View's context to invoke when the view
is clicked.

5 android:visibility
This controls the initial visibility of the view.

Example
This example will take you through simple steps to show how to create your
own Android application using Linear Layout and ImageButton.

Step Description

1 You will use Android studio IDE to create an Android application and name it
as myapplication under a package com.example.myapplication as explained in
the Hello World Example chapter.

2 Modify src/MainActivity.java file to add a click event.

3 Modify the default content of res/layout/activity_main.xml file to include Android


UI control.

4 No need to define default constants in android, Android studio takes care of


default constants.
5 Run the application to launch Android emulator and verify the result of the
changes done in the application.

Following is the content of the modified main activity


file src/com.example.myapplication/MainActivity.java. This file can include
each of the fundamental lifecycle methods.
In the below example abc indicates the image of tutorialspoint

package com.example.myapplication;

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

public class MainActivity extends Activity {


ImageButton imgButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgButton =(ImageButton)findViewById(R.id.imageButton);
imgButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"You
download is
resumed",Toast.LENGTH_LONG).show();
}
});
}
}
Following will be the content of res/layout/activity_main.xml file −
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView android:text="Tutorials Point"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30dp"
android:layout_alignParentTop="true"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:src="@drawable/abc"/>

</RelativeLayout>
Following will be the content of res/values/strings.xml to define these new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">myapplication</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.myapplication.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>
</application>
</manifest>
Let's try to run your myapplication application. I assume you had created
your AVD while doing environment setup. To run the app from Android Studio,
open one of your project's activity files and click Run icon from the toolbar.
Android Studio installs the app on your AVD and starts it and if everything is
fine with your setup and application, it will display following Emulator window −

The following screen will appear after ImageButton is clicked,It shows a toast
message.
4.1.6 Toggle Button:
A ToggleButton displays checked/unchecked states as a button. It is basically
an on/off button with a light indicator.

Toggle Button

4.1.6(A) ToggleButton Attributes:


Following are the important attributes related to ToggleButton control. You can
check Android official documentation for complete list of attributes and related
methods which you can use to change these attributes are run time.
Sr.No Attribute & Description
.

1 android:disabledAlpha
This is the alpha to apply to the indicator when disabled.

2 android:textOff
This is the text for the button when it is not checked.

3 android:textOn
This is the text for the button when it is checked.

Inherited from android.widget.TextView Class −

Sr.No Attribute & Description


.

1 android:autoText
If set, specifies that this TextView has a textual input method and
automatically corrects some common spelling errors.

2 android:drawableBottom
This is the drawable to be drawn below the text.

3 android:drawableRight
This is the drawable to be drawn to the right of the text.

4 android:editable
If set, specifies that this TextView has an input method.

5 android:text
This is the Text to display.

Inherited from android.view.View Class −

Sr.No. Attribute & Description

1 android:background
This is a drawable to use as the background.

2 android:contentDescription
This defines text that briefly describes content of the view.

3 android:id
This supplies an identifier name for this view,

4 android:onClick
This is the name of the method in this View's context to invoke when the
view is clicked.

5 android:visibility
This controls the initial visibility of the view.

Example
This example will take you through simple steps to show how to create your
own Android application using Linear Layout and ToggleButton.

Ste Description
p

1 You will use Android studio IDE to create an Android application and name it
as My Application under a package com.example.saira_000.myapplication as
explained in the Hello World Example chapter.

2 Modify src/MainActivity.java file to add a click event.

2 Modify the default content of res/layout/activity_main.xml file to include


Android UI control.

3 No need to declare default constants.Android studio takes care of default


constants at string.xml

4 Run the application to launch Android emulator and verify the result of the
changes done in the application.

Following is the content of the modified main activity


file src/MainActivity.java. This file can include each of the fundamental
lifecycle methods.
In the below example abc indicates the image of tutorialspoint

package com.example.saira_000.myapplication;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends ActionBarActivity {


ToggleButton tg1,tg2;
Button b1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tg1=(ToggleButton)findViewById(R.id.toggleButton);
tg2=(ToggleButton)findViewById(R.id.toggleButton2);
b1=(Button)findViewById(R.id.button2);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StringBuffer result = new StringBuffer();
result.append("You have clicked first ON
Button-:) ").append(tg1.getText());
result.append("You have clicked Second ON Button
-:) ").append(tg2.getText());
Toast.makeText(MainActivity.this,
result.toString(),Toast.LENGTH_SHORT).show();
}
});
}
}
Following will be the content of res/layout/activity_main.xml file −
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_above="@+id/imageButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="40dp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="On"
android:id="@+id/toggleButton"
android:checked="true"
android:layout_below="@+id/imageButton"
android:layout_toEndOf="@+id/button2/>
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Off"
android:id="@+id/toggleButton2"
android:checked="true"
android:layout_alignTop="@+id/toggleButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
android:text="ClickMe"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Following will be the content of res/values/strings.xml to define these new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My Application</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.saira_000.myapplication" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.MyApplication.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>
</application>
</manifest>
Let's try to run your My Application application. I assume you had created
your AVD while doing environment setup. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Android studio installs the app on your AVD and starts it and if everything is
fine with your setup and application, it will display following Emulator window −
The following screen will appear −

If you have clicked first on Button, you would get a message on Toast as You
have clicked first ON Button-:) or else if you clicked on second on button,
you would get a message on Toast as You have clicked Second ON Button
-:)
4.1.7 Radio Button:
A RadioButton has two states: either checked or unchecked.This allows the
user to select one option from a set.

Radio Button

Example
This example will take you through simple steps to show how to create your
own Android application using Linear Layout and RadioButton.

Step Description

1 You will use Android studio to create an Android application and name it as My
Application under a package com.example.saira_000.myapplication as
explained in the Hello World Example chapter.

2 Modify src/MainActivity.java file to add a click event.

2 Modify the default content of res/layout/activity_main.xml file to include Android


UI control.

3 Android studio takes care of default constants so no need to declare default


constants at string.xml file

4 Run the application to launch Android emulator and verify the result of the
changes done in the application.
Following is the content of the modified main activity
file src/MainActivity.java. This file can include each of the fundamental
lifecycle methods.
In the below example abc indicates the image of tutorialspoint

package com.example.saira_000.myapplication;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {


RadioGroup rg1;
RadioButton rb1;
Button b1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerRadioButton();
}
private void addListenerRadioButton() {
rg1 = (RadioGroup) findViewById(R.id.radioGroup);
b1 = (Button) findViewById(R.id.button2);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int selected=rg1.getCheckedRadioButtonId();
rb1=(RadioButton)findViewById(selected);
Toast.makeText(MainActivity.this,rb1.getText(),Toast.LENGTH_L
ONG).show();
}
});
}
}
Following will be the content of res/layout/activity_main.xml file −
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Example of Radio Button"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_above="@+id/imageButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="40dp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
android:text="ClickMe"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@+id/imageButton"
android:layout_alignLeft="@+id/textView2"
android:layout_alignStart="@+id/textView2">
<RadioButton
android:layout_width="142dp"
android:layout_height="wrap_content"
android:text="JAVA"
android:id="@+id/radioButton"
android:textSize="25dp"
android:textColor="@android:color/holo_red_light"
android:checked="false"
android:layout_gravity="center_horizontal" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ANDROID"
android:id="@+id/radioButton2"
android:layout_gravity="center_horizontal"
android:checked="false"
android:textColor="@android:color/holo_red_dark"
android:textSize="25dp" />
<RadioButton
android:layout_width="136dp"
android:layout_height="wrap_content"
android:text="HTML"
android:id="@+id/radioButton3"
android:layout_gravity="center_horizontal"
android:checked="false"
android:textSize="25dp"
android:textColor="@android:color/holo_red_dark" />
</RadioGroup>
</RelativeLayout>
Following will be the content of res/values/strings.xml to define these new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My Application</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.saira_000.myapplication" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.My
Application.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>
</application>
</manifest>
Let's try to run your My Application application. I assume you had created
your AVD while doing environment setup. To run the app from Android Studio,
open one of your project's activity files and click Run icon from the toolbar.
Android Studio installs the app on your AVD and starts it and if everything is
fine with your setup and application, it will display following Emulator window −
If User selected any of a Radio Button, It should give same name on Toast
message. for suppose, if User selected JAVA, it gives a toast message as
JAVA

4.1.8 Radio Group:


A RadioGroup class is used for set of radio buttons.
If we check one radio button that belongs to a radio group, it automatically
unchecks any previously checked radio button within the same group.

4.1.8(A) RadioGroup Attributes:


Following are the important attributes related to RadioGroup control. You can
check Android official documentation for complete list of attributes and related
methods which you can use to change these attributes are run time.

Attribute Description

android:checkedButton This is the id of child radio button that should be checked by


default within this radio group.

Inherited from android.view.View Class −

Sr.No. Attribute & Description

1 android:background
This is a drawable to use as the background.

2 android:contentDescription
This defines text that briefly describes content of the view.

3 android:id
This supplies an identifier name for this view

4 android:onClick
This is the name of the method in this View's context to invoke when the view
is clicked.

5 android:visibility
This controls the initial visibility of the view.

Example
This example will take you through simple steps to show how to create your
own Android application using Linear Layout and RadioGroup.

Step Description

1 You will use Android studio IDE to create an Android application and name it
as My Application under a package com.example.saira_000.myapplication; as
explained in the Hello World Example chapter.

2 Modify src/MainActivity.java file to add a click event.

2 Modify the default content of res/layout/activity_main.xml file to include Android


UI control.

3 No need to change default constants at res/values/strings.xml, android studio


takes care of default constants.

4 Run the application to launch Android emulator and verify the result of the
changes done in the application.

Following is the content of the modified main activity


file src/MainActivity.java. This file can include each of the fundamental
lifecycle methods.
In the below example abc indicates the image of tutorialspoint
package com.example.saira_000.myapplication;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends Activity {


private RadioGroup radioSexGroup;
private RadioButton radioSexButton;
private Button btnDisplay;

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

radioSexGroup=(RadioGroup)findViewById(R.id.radioGroup);

btnDisplay=(Button)findViewById(R.id.button);

btnDisplay.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
int
selectedId=radioSexGroup.getCheckedRadioButtonId();

radioSexButton=(RadioButton)findViewById(selectedId);

Toast.makeText(MainActivity.this,radioSexButton.getText(),Toa
st.LENGTH_SHORT).show();
}
});
}
}
Following will be the content of res/layout/activity_main.xml file −
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Radio button"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="35dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorialspoint"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView"
android:textSize="35dp"
android:textColor="@android:color/holo_green_dark" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_alignLeft="@+id/textView"
android:layout_alignStart="@+id/textView"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView" />

<RadioGroup
android:layout_width="fill_parent"
android:layout_height="90dp"
android:layout_below="@+id/imageView"
android:layout_marginTop="58dp"
android:weightSum="1"
android:id="@+id/radioGroup"
android:layout_alignLeft="@+id/textView2"
android:layout_alignStart="@+id/textView2"
android:layout_alignRight="@+id/textView3"
android:layout_alignEnd="@+id/textView3">

<RadioButton
android:layout_width="wrap_content"
android:layout_height="55dp"
android:text="Male"
android:id="@+id/radioButton"
android:layout_gravity="center_horizontal"
android:checked="false"
android:textSize="25dp" />

<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:id="@+id/radioButton2"
android:layout_gravity="center_horizontal"
android:checked="false"
android:textSize="25dp"
android:layout_weight="0.13" />
</RadioGroup>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Are you?"
android:id="@+id/textView3"
android:textSize="35dp"
android:layout_below="@+id/imageView"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button"
android:layout_gravity="center_horizontal"
android:layout_below="@+id/radioGroup"
android:layout_centerHorizontal="true" />

</RelativeLayout>
Following will be the content of res/values/strings.xml to define these new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My Applicaiton</string>
<string name="example_radiogroup">Example showing
RadioGroup</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.saira_000.myapplication" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.My
Application.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>

</application>
</manifest>
Let's try to run your My Application application. I assume you had created
your AVD while doing environment setup. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Android studio installs the app on your AVD and starts it and if everything is
fine with your setup and application, it will display following Emulator window −
The following screen will appear, here we have a RadioGroup.
Need to select male or female radio button then click on new button. if you do
above steps without fail, you would get a toast message after clicked by new
button

4.1.9 CheckBox:
A CheckBox is an on/off switch that can be toggled by the user. You should
use check-boxes when presenting users with a group of selectable options that
are not mutually exclusive.

CheckBox
4.1.9(A) CheckBox Attributes:
Following are the important attributes related to CheckBox control. You can
check Android official documentation for complete list of attributes and related
methods which you can use to change these attributes are run time.
Inherited from android.widget.TextView Class −

Sr.No Attribute & Description

android:autoText
1
If set, specifies that this TextView has a textual input method and automatically
corrects some common spelling errors.

2 android:drawableBottom
This is the drawable to be drawn below the text.

3 android:drawableRight
This is the drawable to be drawn to the right of the text.

4 android:editable
If set, specifies that this TextView has an input method.

5 android:text
This is the Text to display.

Inherited from android.view.View Class –

Sr.No Attribute & Description

1 android:background
This is a drawable to use as the background.
2 android:contentDescription
This defines text that briefly describes content of the view.

3 android:id
This supplies an identifier name for this view.

android:onClick
4
This is the name of the method in this View's context to invoke when the view
is clicked.

5 android:visibility
This controls the initial visibility of the view.

Example
This example will take you through simple steps to show how to create your
own Android application using Linear Layout and CheckBox.

Step Description

1 You will use Android Studio IDE to create an Android application and name it
as myapplication under a package com.example.myapplication as explained in
the Hello World Example chapter.

2 Modify src/MainActivity.java file to add a click event.

3 Modify the default content of res/layout/activity_main.xml file to include Android


UI control.

4 No need to declare default string constants. Android studio takes care of default
constants at string.xml
5 Run the application to launch Android emulator and verify the result of the
changes done in the application.

Following is the content of the modified main activity


file src/MainActivity.java. This file can include each of the fundamental
lifecycle methods.
package com.example.myapplication;

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

import android.view.View;
import android.view.View.OnClickListener;

import android.widget.CheckBox;
import android.widget.Toast;

public class MainActivity extends Activity {


CheckBox ch1,ch2;
Button b1,b2;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ch1=(CheckBox)findViewById(R.id.checkBox1);
ch2=(CheckBox)findViewById(R.id.checkBox2);
b1=(Button)findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StringBuffer result = new StringBuffer();
result.append("Thanks : ").append(ch1.isChecked());
result.append("\nThanks: ").append(ch2.isChecked());
Toast.makeText(MainActivity.this, result.toString(),
Toast.LENGTH_LONG).show();
}
});
}
}
Following will be the content of res/layout/activity_main.xml file −
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Example of checkbox"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Do you like Tutorials Point"
android:layout_above="@+id/button"
android:layout_centerHorizontal="true" />
<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Do you like android "
android:checked="false"
android:layout_above="@+id/checkBox1"
android:layout_alignLeft="@+id/checkBox1"
android:layout_alignStart="@+id/checkBox1" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/checkBox1"
android:layout_below="@+id/textView1"
android:layout_marginTop="39dp"
android:text="Tutorials point"
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_alignRight="@+id/textView1"
android:layout_alignEnd="@+id/textView1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ok"
android:id="@+id/button"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/checkBox1"
android:layout_alignStart="@+id/checkBox1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"
android:id="@+id/button2"
android:layout_alignParentBottom="true"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Following will be the content of res/values/strings.xml to define these new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">MyApplication</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.myapplication.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>
</application>
</manifest>
Let's try to run your MyApplication application. I assume you had created
your AVD while doing environment setup. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Android studio installs the app on your AVD and starts it and if everything is
fine with your setup and application, it will display following Emulator window −
User needs you check on either do you like android check box or do you like
tutorials point check box. and press ok button, if does all process correctly, it
gonna be shown toast message as Thanks. Or else do press on cancel button,
if user presses cancel button it going to close the application

4.1.10 Progress Bars:


Progress bars are used to show progress of a task. For example, when you are
uploading or downloading something from the internet, it is better to show the
progress of download/upload to the user.
In android there is a class called ProgressDialog that allows you to create
progress bar. In order to do this, you need to instantiate an object of this class.
Its syntax is.
ProgressDialog progress = new ProgressDialog(this);
Now you can set some properties of this dialog. Such as, its style, its text etc.
progress.setMessage("Downloading Music :) ");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setIndeterminate(true);
Apart from these methods, there are other methods that are provided by the
ProgressDialog class
Sr. Title & description
No

1 getMax()
This method returns the maximum value of the progress.

2 incrementProgressBy(int diff)
This method increments the progress bar by the difference of value passed
as a parameter.

3 setIndeterminate(boolean indeterminate)
This method sets the progress indicator as determinate or indeterminate.

4 setMax(int max)
This method sets the maximum value of the progress dialog.

5 setProgress(int value)
This method is used to update the progress dialog with some specific value.

6 show(Context context, CharSequence title, CharSequence message)


This is a static method, used to display progress dialog.

Example
This example demonstrates the horizontal use of the progress dialog which is
in fact a progress bar. It display a progress bar on pressing the button.
To experiment with this example, you need to run this on an actual device after
developing the application according to the steps below.

Steps Description
1 You will use Android studio to create an Android application under a
package com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add progress code to display the


progress dialog.

3 Modify res/layout/activity_main.xml file to add respective XML code.

4 Run the application and choose a running android device and install the
application on it and verify the results.

Following is the content of the modified main activity


file src/MainActivity.java.
package com.example.sairamkrishna.myapplication;

import android.app.ProgressDialog;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends ActionBarActivity {


Button b1;
private ProgressDialog progress;

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button2);
}

public void download(View view){


progress=new ProgressDialog(this);
progress.setMessage("Downloading Music");

progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setIndeterminate(true);
progress.setProgress(0);
progress.show();

final int totalProgressTime = 100;


final Thread t = new Thread() {
@Override
public void run() {
int jumpTime = 0;

while(jumpTime < totalProgressTime) {


try {
sleep(200);
jumpTime += 5;
progress.setProgress(jumpTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
t.start();
}
}
Modify the content of res/layout/activity_main.xml to the following −
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"
android:text="Progress bar" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Download"
android:onClick="download"
android:id="@+id/button2"
android:layout_marginLeft="125dp"
android:layout_marginStart="125dp"
android:layout_centerVertical="true" />

</RelativeLayout>
This is the default AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="@mipmap/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>

</application>
</manifest>
Let's try to run your application. We assume, you have connected your actual
Android Mobile device with your computer. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Before starting your application, Android studio will display following window to
select an option where you want to run your Android application.

Select your mobile device as an option and then check your mobile device
which will display following screen −

Just press the button to start the Progress bar. After pressing, following screen
would appear −
It will continuously update itself.

4.2 .1 ListView:
 Android ListView is a view which groups several items and display them
in vertical scrollable list. The list items are automatically inserted to the
list using an Adapter that pulls content from a source such as an array or
database.


 List View
 An adapter actually bridges between UI components and the data source
that fill data into UI Component. Adapter holds the data and send the
data to adapter view, the view can takes the data from adapter view and
shows the data on different views like as spinner, list view, grid view etc.
 The ListView and GridView are subclasses of AdapterView and they
can be populated by binding them to an Adapter, which retrieves data
from an external source and creates a View that represents each data
entry.
 Android provides several subclasses of Adapter that are useful for
retrieving different kinds of data and building views for an AdapterView
( i.e. ListView or GridView). The common adapters
are ArrayAdapter,Base
Adapter, CursorAdapter, SimpleCursorAdapter,SpinnerAdapter and
WrapperListAdapter. We will see separate examples for both the
adapters.

4.2.1(A) ListView Attributes:


Following are the important attributes specific to GridView −

Sr.No Attribute & Description

1 android:id
This is the ID which uniquely identifies the layout.

2 android:divider
This is drawable or color to draw between list items.

3 android:dividerHeight
This specifies height of the divider. This could be in px, dp, sp, in, or mm.

4 android:entries
Specifies the reference to an array resource that will populate the ListView.

5 android:footerDividersEnabled
When set to false, the ListView will not draw the divider before each footer
view. The default value is true.
6 android:headerDividersEnabled
When set to false, the ListView will not draw the divider after each header
view. The default value is true.

ArrayAdapter:
You can use this adapter when your data source is an array. By default,
ArrayAdapter creates a view for each array item by calling toString() on each
item and placing the contents in a TextView. Consider you have an array of
strings you want to display in a ListView, initialize a new ArrayAdapter using a
constructor to specify the layout for each string and the string array −
ArrayAdapter adapter = new
ArrayAdapter<String>(this,R.layout.ListView,StringArray);
Here are arguments for this constructor −
 First argument this is the application context. Most of the case, keep
it this.
 Second argument will be layout defined in XML file and
having TextView for each string in the array.
 Final argument is an array of strings which will be populated in the text
view.
Once you have array adapter created, then simply call setAdapter() on
your ListView object as follows −
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
You will define your list view under res/layout directory in an XML file. For our
example we are going to using activity_main.xml file.
Example
Following is the example which will take you through simple steps to show how
to create your own Android application using ListView. Follow the following
steps to modify the Android application we created in Hello World
Example chapter –

Ste Description
p
1 You will use Android Studio IDE to create an Android application and name it
as ListDisplay under a package com.example.ListDisplay as explained in
the Hello World Example chapter.

2 Modify the default content of res/layout/activity_main.xml file to include


ListView content with the self explanatory attributes.

3 No need to change string.xml, Android studio takes care of default string


constants.

4 Create a Text View file res/layout/activity_listview.xml. This file will have


setting to display all the list items. So you can customize its fonts, padding,
color etc. using this file.

6 Run the application to launch Android emulator and verify the result of the
changes done in the application.

Following is the content of the modified main activity


file src/com.example.ListDisplay/ListDisplay.java. This file can include each
of the fundamental life cycle methods.
package com.example.ListDisplay;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ListDisplay extends Activity {


// Array of strings...
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);
ArrayAdapter adapter = new ArrayAdapter<String>(this,
R.layout.activity_listview, mobileArray);
ListView listView = (ListView)
findViewById(R.id.mobile_list);
listView.setAdapter(adapter);
}
}
Following will be the content of res/layout/activity_main.xml file −
<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"
tools:context=".ListActivity" >

<ListView
android:id="@+id/mobile_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Following will be the content of res/values/strings.xml to define two new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">ListDisplay</string>
<string name="action_settings">Settings</string>
</resources>
Following will be the content of res/layout/activity_listview.xml file −
<?xml version="1.0" encoding="utf-8"?>
<!-- Single List Item Design -->

<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold" >
</TextView>
Let's try to run our modified Hello World! application we just modified. I
assume you had created your AVD while doing environment set-up. To run the
app from Android studio, open one of your project's activity files and click
Run icon from the tool bar. Android studio installs the app on your AVD and
starts it and if everything is fine with your set-up and application, it will display
following Emulator window −

SimpleCursorAdapter:
You can use this adapter when your data source is a database Cursor. When
using SimpleCursorAdapter, you must specify a layout to use for each row in
the Cursor and which columns in the Cursor should be inserted into which
views of the layout.
For example, if you want to create a list of people's names and phone
numbers, you can perform a query that returns a Cursor containing a row for
each person and columns for the names and numbers. You then create a
string array specifying which columns from the Cursor you want in the layout
for each result and an integer array specifying the corresponding views that
each column should be placed −
String[] fromColumns = {ContactsContract.Data.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
int[] toViews = {R.id.display_name, R.id.phone_number};
When you instantiate the SimpleCursorAdapter, pass the layout to use for each
result, the Cursor containing the results, and these two arrays −
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.person_name_and_number, cursor, fromColumns,
toViews, 0);
ListView listView = getListView();
listView.setAdapter(adapter);
The SimpleCursorAdapter then creates a view for each row in the Cursor using
the provided layout by inserting each from Columns item into the
corresponding toViews view.

4.2.2 GridView:
Android GridView shows items in two-dimensional scrolling grid (rows &
columns) and the grid items are not necessarily predetermined but they
automatically inserted to the layout using a ListAdapter

Grid view

An adapter actually bridges between UI components and the data source that
fill data into UI Component. Adapter can be used to supply the data to like
spinner, list view, grid view etc.
The ListView and GridView are subclasses of AdapterView and they can be
populated by binding them to an Adapter, which retrieves data from an
external source and creates a View that represents each data entry.

4.2.2(A) GridView Attributes:


Following are the important attributes specific to GridView −

Sr.No Attribute & Description

1 android:id
This is the ID which uniquely identifies the layout.

android:columnWidth
2
This specifies the fixed width for each column. This could be in px, dp, sp,
in, or mm.

android:gravity
3
Specifies the gravity within each cell. Possible values are top, bottom, left,
right, center, center_vertical, center_horizontal etc.

android:horizontalSpacing
4
Defines the default horizontal spacing between columns. This could be in
px, dp, sp, in, or mm.

android:numColumns
5 Defines how many columns to show. May be an integer value, such as
"100" or auto_fit which means display as many columns as possible to fill
the available space.

6 android:stretchMode
Defines how columns should stretch to fill the available empty space, if any.
This must be either of the values −
 none − Stretching is disabled.
 spacingWidth − The spacing between each column is stretched.
 columnWidth − Each column is stretched equally.
 spacingWidthUniform − The spacing between each column is
uniformly stretched..

android:verticalSpacing
7
Defines the default vertical spacing between rows. This could be in px, dp,
sp, in, or mm.

Example
This example will take you through simple steps to show how to create your
own Android application using GridView. Follow the following steps to modify
the Android application we created in Hello World Example chapter −

Step Description

1 You will use Android studio IDE to create an Android application and name it
as HelloWorld under a package com.example.helloworld as explained in the Hello
World Example chapter.

2 Modify the detault content of res/layout/activity_main.xml file to include GridView


content with the self explanatory attributes.

3 No need to change string.xml, Android studio takes care of defaults strings which
are placed at string.xml

4 Let's put few pictures in res/drawable-hdpi folder. I have put sample0.jpg,


sample1.jpg, sample2.jpg, sample3.jpg, sample4.jpg, sample5.jpg, sample6.jpg
and sample7.jpg.

5 Create a new class called ImageAdapter under a package


com.example.helloworld that extends BaseAdapter. This class will implement
functionality of an adapter to be used to fill the view.
6 Run the application to launch Android emulator and verify the result of the
changes done in the application.

Following is the content of the modified main activity


file src/com.example.helloworld/MainActivity.java. This file can include
each of the fundamental lifecycle methods.
package com.example.helloworld;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.GridView;

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
}
}
Following will be the content of res/layout/activity_main.xml file −
<?xml version="1.0" encoding="utf-8"?>
<GridView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
Following will be the content of res/values/strings.xml to define two new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">HelloWorld</string>
<string name="action_settings">Settings</string>
</resources>
Following will be the content
of src/com.example.helloworld/ImageAdapter.java file −
package com.example.helloworld;

import android.content.Context;

import android.view.View;
import android.view.ViewGroup;

import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class ImageAdapter extends BaseAdapter {


private Context mContext;
// Constructor
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}

public Object getItem(int position) {


return null;
}

public long getItemId(int position) {


return 0;
}
// create a new ImageView for each item referenced by the
Adapter
public View getView(int position, View convertView,
ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new
GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
}
else
{
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// Keep all Images in array
public Integer[] mThumbIds = {
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7,
R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7,
R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7
};
}
Let's try to run our modified Hello World! application we just modified. I
assume you had created your AVD while doing environment setup. To run the
app from Android Studio, open one of your project's activity files and click
Run icon from the toolbar. Android studio installs the app on your AVD and
starts it and if everything is fine with your setup and application, it will display
following Emulator window −
Sub-Activity Example:
Let's extend the functionality of above example where we will show selected
grid image in full screen. To achieve this we need to introduce a new activity.
Just keep in mind for any activity we need perform all the steps like we have to
implement an activity class, define that activity in AndroidManifest.xml file,
define related layout and finally link that sub-activity with the main activity by it
in the main activity class. So let's follow the steps to modify above example –

Ste Description
p

1 You will use Android studio IDE to create an Android application and name it
as HelloWorld under a package com.example.helloworld as explained in
the Hello World Example chapter.

2 Create a new Activity class as SingleViewActivity.java under a


package com.example.helloworld as shown below.
3 Create new layout file for the new activity under res/layout/ folder. Let's name
this XML file as single_view.xml.

4 Define your new activity in AndroidManifest.xml file using <activity.../> tag. An


application can have one or more activities without any restrictions.

5 Run the application to launch Android emulator and verify the result of the
changes done in the application.

Following is the content of the modified main activity


file src/com.example.helloworld/MainActivity.java. This file can include
each of the fundamental life cycle methods.
package com.example.helloworld;

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

import android.view.Menu;
import android.view.View;

import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridview = (GridView)
findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new
OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View v, int position, long id){
// Send intent to SingleViewActivity
Intent i = new Intent(getApplicationContext(),
SingleViewActivity.class);
// Pass image index
i.putExtra("id", position);
startActivity(i);
}
});
}
}
Following will be the content of new activity
file src/com.example.helloworld/SingleViewActivity.java file −
package com.example.helloworld;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;

public class SingleViewActivity extends Activity {


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_view);
// Get intent data
Intent i = getIntent();
// Selected image id
int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
ImageView imageView = (ImageView)
findViewById(R.id.SingleView);
imageView.setImageResource(imageAdapter.mThumbIds[position]);
}
}
Following will be the content of res/layout/single_view.xml file −
<?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" >
<ImageView android:id="@+id/SingleView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
Following will be the content of AndroidManifest.xml to define two new
constants −
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld">
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.helloworld.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=".SingleViewActivity"></activity>
</application>
</manifest>
Let's try to run our modified Hello World! application we just modified. I
assume you had created your AVD while doing environment setup. To run the
app from Android studio, open one of your project's activity files and click
Run icon from the toolbar. Android studio installs the app on your AVD and
starts it and if everything is fine with your setup and application, it will display
following Emulator window −
Now if you click on either of the images it will be displayed as a single image,
for example−
4.2.3 Image View:
In Android, ImageView class is used to display an image file in application.
Image file is easy to use but hard to master in Android, because of the various
screen sizes in Android devices. An android is enriched with some of the best
UI design widgets that allows us to build good looking and attractive UI based
application.
Important Note: ImageView comes with different configuration options to
support different scale types. Scale type options are used for scaling the
bounds of an image to the bounds of the imageview. Some of them scaleTypes
configuration properties are center, center_crop, fit_xy, fitStart etc. You can
read our ScaleType tutorial to learn all details on it.
Below is an ImageView code in XML:
Make sure to save lion image in drawable folder

<ImageView
android:id="@+id/simpleImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/lion" />

4.2.3(A) Attributes of ImageView:


1. id: id is an attribute used to uniquely identify a image view in android. Below is the
example code in which we set the id of a image view.
2. src: src is an attribute used to set a source file or you can say image in your
imageview to make your layout attractive.
3. background: background attribute is used to set the background of a ImageView.
We can set a color or a drawable in the background of a ImageView.
4. padding: padding attribute is used to set the padding from left, right, top or bottom
of the Imageview.

 paddingRight: set the padding from the right side of the image view.
 paddingLeft: set the padding from the left side of the image view.
 paddingTop: set the padding from the top side of the image view.
 paddingBottom: set the padding from the bottom side of the image view.
 padding: set the padding from the all side’s of the image view.

5. scaleType: scaleType is an attribute used to control how the image should be re-
sized or moved to match the size of this image view. The value for scale type attribute
can be fit_xy, center_crop, fitStart etc.
Example of ImageView:
Below is the example of imageview in which we display two animal images of
Lion and Monkey. And whenever user click on an image Animal name is
displayed as toast on screen. Below is the final output and code:

Step 1: Create a new project and name it ImageViewExample.

In this step we create a new project in android studio by filling all the
necessary details of the app like app name, package name, api versions etc.

Select File -> New -> New Project and Fill the forms and click "Finish"
button.
Step 2: Download two images lion and monkey from the web. Now save those
images in the drawable folder of your project.

Step 3: Now open res -> layout -> activity_main.xml (or) main.xml and add
following code:

In this step we add the code for displaying an image view on the screen in
a relative layout. Here make sure you have already saved two images name lion
and monkey in your drawable folder.

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

<ImageView
android:id="@+id/simpleImageViewLion"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:scaleType="fitXY"
android:src="@drawable/lion" />

<ImageView
android:id="@+id/simpleImageViewMonkey"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_below="@+id/simpleImageViewLion"
android:layout_marginTop="10dp"
android:scaleType="fitXY"
android:src="@drawable/monkey" />

</RelativeLayout>

Step 4: Now open app -> java -> package -> MainActivity.java and add the
following code:
In this step we add the code to initiate the image view’s and then perform click
event on them.

package example.abhiandriod.imageviewexample;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView simpleImageViewLion = (ImageView)
findViewById(R.id.simpleImageViewLion);//get the id of first image view
ImageView simpleImageViewMonkey = (ImageView)
findViewById(R.id.simpleImageViewMonkey);//get the id of second image
view
simpleImageViewLion.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Lion",
Toast.LENGTH_LONG).show();//display the text on image click event
}
});
simpleImageViewMonkey.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Monkey",
Toast.LENGTH_LONG).show();//display the text on image click event
}
});
}

Output:
Now start AVD in Emulator and run the App. You will see the images of Lion and
Monkey displayed on screen. Click on any Animal image and his name will
appear on Screen. We clicked on Lion.
4.2.4 ScrollView:
In android ScrollView can hold only one direct child. This means that, if you have
complex layout with more views(Buttons, TextViews or any other view) then you must
enclose them inside another standard layout like Table Layout, Relative
Layout or Linear Layout. You can specify layout_width and layout_height to adjust
width and height of screen. You can specify height and width in dp(density pixel) or
px(pixel). Then after enclosing them in a standard layout, enclose the whole layout
in ScrollView to make all the element or views scrollable.
ScrollView in Android Studio Design: It is present inside Containers >> ScrollView or
HorizontalScrollView
ScrollView Syntax:

<ScrollView
android:id="@+id/scrollView"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- add child view’s here -->

</ScrollView>

4.2.4(A) Attributes Of Scroll View:


ScrollView and HorizontalScrollView has same attributes, the only difference is
scrollView scroll the child items in vertical direction while horizontal scroll view
scroll the child items in horizontal direction.
Now let’s we discuss about the attributes that helps us to configure a ScrollView
and its child controls. Some of the most important attributes you will use with
ScrollView include:
1. id: In android, id attribute is used to uniquely identify a ScrollView.
Below is id attribute’s example code with explanation included.

<ScrollView
android:id="@+id/scrollView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>

2. scrollbars: In android, scrollbars attribute is used to show the scrollbars in


horizontal or vertical direction. The possible Value of scrollbars is vertical,
horizontal or none. By default scrollbars is shown in vertical direction in
scrollView and in horizontal direction in HorizontalScrollView.
Below is scrollbars attribute’s example code in which we set the scrollbars in
vertical direction.

< HorizontalScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="vertical"/><!--scrollbars in vertical direction-->

Example of ScrollView In Android Studio:


Example 1: In this example we will use 10 button and scroll them using
ScrollView in vertical direction. Below is the code and final Output we will create:

Step 1: Create a new project in Android Studio and name it scrollviewExample.

Select File -> New -> New Project -> Android Application Project (or) Android
Project. Fill the forms and click “Finish” button.

Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add below
code. Here we are creating a Relative Layout having 10 buttons which are nested
in Linear Layout and then in ScrollView.
Important Note: Remember ScrollView can hold only one direct child. So we
have to jointly put 10 buttons inside Linear Layout to make it one child. And then
we put it inside ScrollView.
<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=".MainActivity">

<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="vertical">

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="20dp"
android:orientation="vertical">

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#f00"
android:text="Button 1"
android:textColor="#fff"
android:textSize="20sp" />

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#0f0"
android:text="Button 2"
android:textColor="#fff"
android:textSize="20sp" />

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#00f"
android:text="Button 3"
android:textColor="#fff"
android:textSize="20sp" />

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#ff0"
android:text="Button 4"
android:textColor="#fff"
android:textSize="20sp" />

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#f0f"
android:text="Button 5"
android:textColor="#fff"
android:textSize="20sp" />

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#f90"
android:text="Button 6"
android:textColor="#fff"
android:textSize="20sp" />

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#f00"
android:text="Button 7"
android:textColor="#ff9"
android:textSize="20sp" />

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#444"
android:text="Button 8"
android:textColor="#fff"
android:textSize="20sp" />

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#ff002211"
android:text="Button 9"
android:textColor="#fff"
android:textSize="20sp" />

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#0f0"
android:text="Button 10"
android:textColor="#fff"
android:textSize="20sp" />

</LinearLayout>

</ScrollView>

</RelativeLayout>

Step 3: Now Open src -> package -> MainActivity.java and paste the below code

package com.example.gourav.scrollviewExample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

Step 4: Now open manifest.xml and paste the below code

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gourav.scrollviewExample" >

<application
android:allowBackup="true"
android:icon="@mipmap/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>
</application>

</manifest>

Step 5: Lastly open res ->values -> strings.xml and paste the below code

<resources>
<string name="app_name">ScrollViewExample</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
</resources>

Output:
Now run the App in Emulator / AVD or in real device. You will see the 10 buttons
which can be scrollable in vertical direction.
4.2.5 Custom Toast Alert:

android.widget.Toast class used to create toast alert message.Toast alert is a


notification message that display for certain amount of time, and automtaically
fades out after set time.Use it to show alert message to user.Use it for
debugging your application.Use toast alert message to show alert from
background sevice,boadcast reciever,getting data from server...etc.
Normal Toast Alert :
//Show alert for short period of time
Toast.makeText(getApplicationContext(), "This is Toast example.",
Toast.LENGTH_SHORT).show();

//Show alert for long period of time


Toast.makeText(getApplicationContext(), "This is Toast example.",
Toast.LENGTH_LONG).show();

Custom Toast Alert :


Using toast.xml file for toast layout.
Using toast_border.xml file for toast style.

Project Structure :
File : res/drawable/toast_border.xml
Create style for custom toast layout.

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


<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="4dp" android:color="#FFFFFFFF" />
<padding android:left="7dp" android:top="7dp"
android:right="7dp" android:bottom="7dp" />
<corners android:radius="4dp" />
</shape>

File : res/layout/toast.xml
This file is used for custom toast layout.

See android:background="@drawable/toast_border" call toast_border.xm


lfile.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/toast_border">
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/image0" />

<TextView
android:paddingLeft="10dp"
android:textColor="#ffffff"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="The image has been uploaded to server."
android:layout_gravity="center_vertical" />

</LinearLayout>

File : res/layout/activity_custom_toast.xml
Create main activity.

<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=".CustomToast"
android:background="#890000">

<TextView
android:paddingTop="20px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

<Button
android:id="@+id/Clickhere"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click here to see custom alert"
/>

</RelativeLayout>

File : src/CustomToast.java
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class CustomToast extends Activity {

private Button Clickhere;

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

Clickhere = (Button) findViewById(R.id.Clickhere);

// Button click listner


Clickhere.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

showCustomAlert();

}
});
}

public void showCustomAlert()


{

Context context = getApplicationContext();


// Create layout inflator object to inflate toast.xml file
LayoutInflater inflater = getLayoutInflater();

// Call toast.xml file for toast layout


View toastRoot = inflater.inflate(R.layout.toast, null);

Toast toast = new Toast(context);

// Set layout to toast


toast.setView(toastRoot);
toast.setGravity(Gravity.CENTER_HORIZONTAL |
Gravity.CENTER_VERTICAL,
0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.show();

}
}

4.3 Time & Date Picker:


Allows you to select the date consisting of day, month and year in your custom
user interface. For this functionality android provides Date Picker and
DatePickerDialog components.

In this section, we are going to demonstrate the use of Date Picker through
DatePickerDialog. DatePickerDialog is a simple dialog containing DatePicker.
In order to show DatePickerDialog , you have to pass the DatePickerDialog id
to showDialog(id_of_dialog) method. Its syntax is given below −
showDialog(999);
On calling this showDialog method, another method
called onCreateDialog gets automatically called. So we have to override that
method too. Its syntax is given below −
@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(this, myDateListener, year,
month, day);
}
return null;
}
In the last step, you have to register the DatePickerDialog listener and override
its onDateSet method. This onDateSet method contains the updated day,
month and year. Its syntax is given below −
private DatePickerDialog.OnDateSetListener myDateListener =
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker arg0, int arg1, int arg2,
int arg3) {
// arg1 = year
// arg2 = month
// arg3 = day
}
};
Apart form date attributes, DatePicker object is also passed into this function.
You can use the following methods of the DatePicker to perform further
operation.

Sr.N Method & description


o

1 getDayOfMonth()
This method gets the selected day of month

2 getMonth()
This method gets the selected month

3 getYear()
This method gets the selected year

4 setMaxDate(long maxDate)
This method sets the maximal date supported by this DatePicker in
milliseconds since January 1, 1970 00:00:00 in getDefault() time zone

5 setMinDate(long minDate)
This method sets the minimal date supported by this NumberPicker in
milliseconds since January 1, 1970 00:00:00 in getDefault() time zone

6 setSpinnersShown(boolean shown)
This method sets whether the spinners are shown

7 updateDate(int year, int month, int dayOfMonth)


This method updates the current date

8 getCalendarView()
This method returns calendar view

9 getFirstDayOfWeek()
This Method returns first day of the week

Example
Here is an example demonstrating the use of DatePickerDialog class. It
creates a basic Date Picker application that allows you to set the Date using
DatePicker Widget
To experiment with this example , you can run this on an actual device or in an
emulator.

Steps Description

1 You will use Android studio to create an Android application and name it as
DatePicker under a package com.example.datepicker.

2 Modify src/MainActivity.java file to add necessary code.

3 Modify the res/layout/activity_main to add respective XML components.

4 Modify the res/values/string.xml to add necessary string components.

5 Run the application and choose a running android device and install the
application on it and verify the results.

Following is the content of the modified main activity


file src/com.example.datepicker/MainActivity.java.
package com.example.datepicker;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;

import android.os.Bundle;

import android.view.Menu;
import android.view.View;

import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {


private DatePicker datePicker;
private Calendar calendar;
private TextView dateView;
private int year, month, day;

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

dateView = (TextView) findViewById(R.id.textView3);


calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);

month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
showDate(year, month+1, day);
}

@SuppressWarnings("deprecation")
public void setDate(View view) {
showDialog(999);
Toast.makeText(getApplicationContext(), "ca",
Toast.LENGTH_SHORT)
.show();
}

@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(this,
myDateListener, year, month, day);
}
return null;
}

private DatePickerDialog.OnDateSetListener myDateListener


= new
DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker arg0,
int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
// arg1 = year
// arg2 = month
// arg3 = day
showDate(arg1, arg2+1, arg3);
}
};

private void showDate(int year, int month, int day) {


dateView.setText(new
StringBuilder().append(day).append("/")
.append(month).append("/").append(year));
}
}
Following is the modified content of the xml res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:onClick="setDate"
android:text="@string/date_button_set" />

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="24dp"
android:text="@string/date_label_set"

android:textAppearance="?android:attr/textAppearanceMedium" /
>

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_marginTop="66dp"
android:layout_toLeftOf="@+id/button1"
android:text="@string/date_view_set"

android:textAppearance="?android:attr/textAppearanceMedium" /
>

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/button1"
android:layout_below="@+id/textView2"
android:layout_marginTop="72dp"
android:text="@string/date_selected"

android:textAppearance="?android:attr/textAppearanceMedium" /
>

</RelativeLayout>
Following is the content of the res/values/string.xml.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">DatePicker</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="date_label_set">Press the button to set the
date</string>
<string name="date_button_set">Set Date</string>
<string name="date_view_set">The Date is: </string>
<string name="date_selected"></string>
</resources>
Let's try to run our DatePicker application we just modified. I assume you had
created your AVD while doing environment set-up. To run the app from
Eclipse, open one of your project's activity files and click Run icon from the
tool bar. Eclipse installs the app on your AVD and starts it and if everything is
fine with your set-up and application, it will display following Emulator window −

Now you can see that the date has already been set at the bottom label. Now
we will change the date through DatePickerDialog by pressing the Set Date
button. On pressing the button following screen would appear.
Now set the required date, and after setting the date, press the Done button.
This dialog will disappear and your newly setted date will start showing at the
screen. This is shown below.

You might also like