KEMBAR78
Chapter 4 Notes | PDF | Android (Operating System) | Button (Computing)
0% found this document useful (0 votes)
13 views88 pages

Chapter 4 Notes

Unit 4 covers designing user interfaces in Android, focusing on various UI components like TextView, EditText, and Button, along with their attributes and usage. It provides step-by-step examples for creating a simple Android application using these components, including code snippets for MainActivity and layout files. Additionally, it explains the attributes of ImageButton and EditText, enhancing the understanding of UI design in Android development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views88 pages

Chapter 4 Notes

Unit 4 covers designing user interfaces in Android, focusing on various UI components like TextView, EditText, and Button, along with their attributes and usage. It provides step-by-step examples for creating a simple Android application using these components, including code snippets for MainActivity and layout files. Additionally, it explains the attributes of ImageButton and EditText, enhancing the understanding of UI design in Android development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 88

Unit 4 : Designing User Interface with View

• 4.1 Text View , Edit Text , Button , Image Button , Toggle Button , Radio Button and Radio Group ,
Checkbox , Progress Bar
• 4.2 List View , Grid View , Image View , Scroll View , Custom Toast alert
• 4.3 Time And Date picker
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.

TextView Attributes
Following are the important attributes related to TextView control.

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

Unit 4 : Designing User Interface with View chapt4 Page 1


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

Unit 4 : Designing User Interface with View chapt4 Page 2


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.

Unit 4 : Designing User Interface with View chapt4 Page 3


Ste Description
p

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 .

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

3 No need to change default string constants at string.xml file. Android studio takes care of default
string 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/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"

Unit 4 : Designing User Interface with View chapt4 Page 4


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>

Unit 4 : Designing User Interface with View chapt4 Page 5


</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 −

Android - EditText Control


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.

Unit 4 : Designing User Interface with View chapt4 Page 6


Styles of edit text
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.

Unit 4 : Designing User Interface with View chapt4 Page 7


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 EditText.

Ste Description
p

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

Unit 4 : Designing User Interface with View chapt4 Page 8


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"

Unit 4 : Designing User Interface with View chapt4 Page 9


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"

Unit 4 : Designing User Interface with View chapt4 Page 10


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 −

Unit 4 : Designing User Interface with View chapt4 Page 11


Android - Button Control
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.

Android button style set


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.No Attribute & Description

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.

Unit 4 : Designing User Interface with View chapt4 Page 12


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.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 ImageButton.

Ste Description
p

Unit 4 : Designing User Interface with View chapt4 Page 13


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();
}
});
}

Unit 4 : Designing User Interface with View chapt4 Page 14


}

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" >

Unit 4 : Designing User Interface with View chapt4 Page 15


<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.

ToggleButton Attributes

Unit 4 : Designing User Interface with View chapt4 Page 16


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 −

Unit 4 : Designing User Interface with View chapt4 Page 17


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

Unit 4 : Designing User Interface with View chapt4 Page 18


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"

Unit 4 : Designing User Interface with View chapt4 Page 19


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 −

Unit 4 : Designing User Interface with View chapt4 Page 20


<?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 −
The following screen will appear −

Unit 4 : Designing User Interface with View chapt4 Page 21


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 -:)

Unit 4 : Designing User Interface with View chapt4 Page 22


Unit 4 : Designing User Interface with View chapt4 Page 23
Android - RadioButton Control

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.

Ste Description
p

Unit 4 : Designing User Interface with View chapt4 Page 24


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

Unit 4 : Designing User Interface with View chapt4 Page 25


public void onClick(View v) {
int selected=rg1.getCheckedRadioButtonId();
rb1=(RadioButton)findViewById(selected);

Toast.makeText(MainActivity.this,rb1.getText(),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: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" />

Unit 4 : Designing User Interface with View chapt4 Page 26


<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 −

Unit 4 : Designing User Interface with View chapt4 Page 27


<?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 −

Unit 4 : Designing User Interface with View chapt4 Page 28


Hi

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.

Android - RadioButton Control

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.

Unit 4 : Designing User Interface with View chapt4 Page 29


Ste Description
p

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();
}

Unit 4 : Designing User Interface with View chapt4 Page 30


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_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: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"

Unit 4 : Designing User Interface with View chapt4 Page 31


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>

Unit 4 : Designing User Interface with View chapt4 Page 32


</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 −

Unit 4 : Designing User Interface with View chapt4 Page 33


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

Android - RadioGroup Control


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.

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

Unit 4 : Designing User Interface with View chapt4 Page 34


android:checkedButto This is the id of child radio button that should be checked by default within this
n 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.

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.

Unit 4 : Designing User Interface with View chapt4 Page 35


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(),Toast.LENGTH_SH
ORT).show();
}

Unit 4 : Designing User Interface with View chapt4 Page 36


});
}
}

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"

Unit 4 : Designing User Interface with View chapt4 Page 37


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>

Unit 4 : Designing User Interface with View chapt4 Page 38


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.

Unit 4 : Designing User Interface with View chapt4 Page 39


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.

Android - CheckBox Control


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.

Unit 4 : Designing User Interface with View chapt4 Page 40


CheckBox
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

Unit 4 : Designing User Interface with View chapt4 Page 41


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 CheckBox.

Ste Description
p

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.

Unit 4 : Designing User Interface with View chapt4 Page 42


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) {

Unit 4 : Designing User Interface with View chapt4 Page 43


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

Unit 4 : Designing User Interface with View chapt4 Page 44


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" >

Unit 4 : Designing User Interface with View chapt4 Page 45


<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 −

Unit 4 : Designing User Interface with View chapt4 Page 46


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.

Android Progress Bar using ProgressDialog


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. No Title & description

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.

Unit 4 : Designing User Interface with View chapt4 Page 47


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.

Step Description
s

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);
}

Unit 4 : Designing User Interface with View chapt4 Page 48


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" />

Unit 4 : Designing User Interface with View chapt4 Page 49


<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.

Unit 4 : Designing User Interface with View chapt4 Page 50


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

Unit 4 : Designing User Interface with View chapt4 Page 51


Just press the button to start the Progress bar. After pressing, following screen would
appear −

Unit 4 : Designing User Interface with View chapt4 Page 52


It will continuously update itself.

Android List View


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.

Unit 4 : Designing User Interface with View chapt4 Page 53


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 WrapperListAdap
ter. We will see separate examples for both the adapters.

ListView Attributes
Following are the important attributes specific to GridView −

Unit 4 : Designing User Interface with View chapt4 Page 54


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 −

Unit 4 : Designing User Interface with View chapt4 Page 55


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",

Unit 4 : Designing User Interface with View chapt4 Page 56


"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>

Unit 4 : Designing User Interface with View chapt4 Page 57


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

Unit 4 : Designing User Interface with View chapt4 Page 58


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.

Android Grid View


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

Unit 4 : Designing User Interface with View chapt4 Page 59


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.

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.

2 android:columnWidth
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.

4 android:horizontalSpacing
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.

android:stretchMode
Defines how columns should stretch to fill the available empty space, if any. This must be either
of the values −
6 ● 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..

Unit 4 : Designing User Interface with View chapt4 Page 60


7 android:verticalSpacing
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 −

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 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;

Unit 4 : Designing User Interface with View chapt4 Page 61


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;

Unit 4 : Designing User Interface with View chapt4 Page 62


}

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

Unit 4 : Designing User Interface with View chapt4 Page 63


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

Unit 4 : Designing User Interface with View chapt4 Page 64


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

Unit 4 : Designing User Interface with View chapt4 Page 65


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>

Unit 4 : Designing User Interface with View chapt4 Page 66


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 −

Unit 4 : Designing User Interface with View chapt4 Page 67


Now if you click on either of the images it will be displayed as a single image, for example−

Unit 4 : Designing User Interface with View chapt4 Page 68


Kindly note above mentioned images have been taken from Android official website.

How to load and display an image in ImageView on Android App?


This example demonstrates how to load and display an image in ImageView on Android App.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required
details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

Unit 4 : Designing User Interface with View chapt4 Page 69


android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical"

tools:context=".MyAndroidAppActivity">

<ImageView

android:id="@+id/imageView1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"/>

<Button

android:id="@+id/btnChangeImage"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Change Image" />

</LinearLayout>

Step 3 − Add the following code to src/MyAndroidAppActivity.java

package com.example.sample;

import android.support.v7.app.AppCompatActivity;

import android.app.Activity;

import android.os.Bundle;

import android.widget.Button;

import android.widget.ImageView;

import android.view.View;

import android.view.View.OnClickListener;

public class MyAndroidAppActivity extends AppCompatActivity {

Button button;

ImageView image;

@Override

protected void onCreate(Bundle savedInstanceState) {

Unit 4 : Designing User Interface with View chapt4 Page 70


super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

addListenerOnButton();

public void addListenerOnButton() {

image=(ImageView) findViewById(R.id.imageView1);

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

button.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View arg0) {

image.setImageResource(R.drawable.ic_launcher_background);

});

Step 4 − Add the following code to Manifests/AndroidManifest.xml

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

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

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:roundIcon="@mipmap/ic_launcher_round"

android:supportsRtl="true"

android:theme="@style/AppTheme">

<activity android:name=".MyAndroidAppActivity">

<intent-filter>

Unit 4 : Designing User Interface with View chapt4 Page 71


<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. I 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. Select your mobile device as an option
and then check your mobile device which will display your default screen −

Unit 4 : Designing User Interface with View chapt4 Page 72


How to create a custom alert dialogs in an android app?
This example demonstrates how do I make a specific text on TextView bold in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required
details to create a new project.
Step 2 − Add the following code to 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:id="@+id/activity_main"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context="MainActivity">

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/buttonShowCustomDialog"

android:onClick="exit"

android:textStyle="normal|bold"

style="@android:style/Widget.DeviceDefault.Button.Inset"

android:layout_alignParentBottom="true"

android:layout_centerHorizontal="true"

android:layout_marginBottom="131dp"

android:text="Click"/>

<TextView

android:text="CLICK TO VIEW CUSTOM ALERT DIALOG"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_above="@+id/buttonShowCustomDialog"

Unit 4 : Designing User Interface with View chapt4 Page 73


android:layout_centerHorizontal="true"

android:layout_marginBottom="86dp"

android:id="@+id/textView"

android:gravity="center"

android:textStyle="normal|bold"

android:textSize="18sp" />

</RelativeLayout>

Step 3 – Create a layout resourse file and add the following code in customdialog.xml

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

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:orientation="vertical" android:layout_width="match_parent"

android:layout_height="match_parent">

<TextView

android:text="Alert...!"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/text"

android:textStyle="normal|bold"

android:textSize="18sp"

android:layout_alignParentTop="true"

android:layout_centerInParent="true"/>

<ImageButton

android:layout_width="35dp"

android:layout_height="35dp"

app:srcCompat="@drawable/ic_block"

Unit 4 : Designing User Interface with View chapt4 Page 74


android:id="@+id/image"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

tools:ignore="ContentDescription,RtlHardcoded" />

<Button

android:id="@+id/dialogButtonOK"

android:layout_width="200dp"

android:layout_height="wrap_content"

android:text="Dismiss"

android:layout_marginTop="23dp"

android:paddingRight="5dp"

android:layout_below="@+id/image"

style="@style/Widget.AppCompat.Button.Colored"

android:textSize="18sp" />

</RelativeLayout>

Step 3 − Add the following code to src/MainActivity.java

import android.app.Dialog;

import android.content.Context;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity{

final Context context = this;

private Button button;

@Override

protected void onCreate(Bundle savedInstanceState) {

Unit 4 : Designing User Interface with View chapt4 Page 75


super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

button = findViewById(R.id.buttonShowCustomDialog);

button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

final Dialog dialog = new Dialog(context);

dialog.setContentView(R.layout.customdialog);

Button dialogButton =
dialog.findViewById(R.id.dialogButtonOK);

dialogButton.setOnClickListener(new View.OnClickListener()
{

@Override

public void onClick(View v) {

dialog.dismiss();

Toast.makeText(getApplicationContext(),"Dismissed..!!",Toast.LENGTH_SHORT
).show();

});

dialog.show();

});

Step 4 - Add the following code to androidManifest.xml

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="app.com.sample">

<application

Unit 4 : Designing User Interface with View chapt4 Page 76


android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:roundIcon="@mipmap/ic_launcher_round"

android:supportsRtl="true"

android:theme="@style/AppTheme">

<activity android:name=".MainActivity">

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

</application>

</manifest>

Let's try to run your application. I 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. Select your mobile device as an option
and then check your mobile device which will display your default screen –

Unit 4 : Designing User Interface with View chapt4 Page 77


Unit 4 : Designing User Interface with View chapt4 Page 78
Unit 4 : Designing User Interface with View chapt4 Page 79
Android - Date Picker
Android Date Picker allows you to select the date consisting of day, month and year in your custom user
interface. For this functionality android provides DatePicker and DatePickerDialog components.
In this tutorial, 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

Unit 4 : Designing User Interface with View chapt4 Page 80


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.No Method & description

Unit 4 : Designing User Interface with View chapt4 Page 81


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.

Step Description
s

Unit 4 : Designing User Interface with View chapt4 Page 82


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);

Unit 4 : Designing User Interface with View chapt4 Page 83


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"

Unit 4 : Designing User Interface with View chapt4 Page 84


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>

Unit 4 : Designing User Interface with View chapt4 Page 85


<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 −

Unit 4 : Designing User Interface with View chapt4 Page 86


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.

Unit 4 : Designing User Interface with View chapt4 Page 87


Unit 4 : Designing User Interface with View chapt4 Page 88

You might also like