You are on page 1of 92

Introducing

User Interfa
Elements in ce
Android
Topics to be covered
0 Android Views and Layouts
0 LinearLayout
0 RelativeLayout
0 TableLayout
0 AdapterViewGroup
0 LIstView
0 GridView
0 Android User interface elements
0 EditText
0 Button
0 CheackBox
0 AlertDialog
Android View Hierarchies
0 In Google Android, in order to interface with the smartphone screen, you
use two core Java classes. These are two of the most important and often
used classes in Android development:
 The View class
 The ViewGroup class
ViewGroup
0 ViewGroup is the invisible container. It holds View and ViewGroup
0 For example, LinearLayout is the ViewGroup that contains Button(View),
and other Layouts also.
0 ViewGroup is the base class for Layouts.
View
0 View objects are the basic building blocks of User Interface(UI) elements
in Android.
View is a simple rectangle box which responds to the user's actions.
Examples are EditText, Button, CheckBox etc..
The View Class
0 The View class serves as the foundation for UI elements that are subclasses
of the View class. Recall that in Java, a subclass is a more specific or
detailed implementation of the class from which it is subclassed.
0 View refers to the android.view.View class, which is the base class of all UI
classes.
0 The View class can also be used to create many lower-level, or more
customized, Java classes. Those classes that are subclassed from the View
class inherit the characteristics of their superclass.

0 For instance, the Button class is subclassed from the TextView class, which
is subclassed from the View class, which is subclassed from the Object
class. The Button class is subclassed from the TextView class because the
Button has a TextView label and is thus a more specialized version of a
TextView; that is, it is a clickable TextView with a button background
appearance.
0 So many UI classes have been subclassed from the View class that there is
a name for them: widgets. All of these widgets are contained in a package
(a collection of classes) called android.widget. For example, you can access
a Button class via this package using android.widget.button.
ViewGroup
0 ViewGroups are layout containers usually collection of user Interface (UI)
elements.
0 Direct subclass of the viewGroup class include AbsoluteLayout,
RelativeLayout, FrameLayout, LinearLayout, SlidingLayout
0 The top level ViewGroup is a parent for view objects and another
ViewGroup objects underneeth it which are called children.
0 So through the concept called nesting ViewGroup objects can contain
other ViewGroup objects but View object (a Button, a TextField, a
CheckBox and so on) can’t contain other view objects.
Most Important Android
Widgets
0 A standard UI is composed of a number of familiar
components that can be used by your application’s users to
control their user experience (often called the UX). These UI
elements include items such as buttons, check boxes, menus,
text fields, dialog boxes, system alerts, and similar widgets.
0 This section covers how to use several of the most important
Android widgets for UI design.
0 First, we’ll cover adding image buttons, text, and images to
your UI. Then you’ll learn about the different types of menus
available. Finally, we’ll cover displaying dialogs, including
alerts, which carry messages to your application user.
Common UI Elements/UI
controls
0 Android has all of the standard UI elements already coded
and ready to use in a single package called android.widget.
0 NOTE: Recall that a package in Java is a collection of ready-
to-use classes that you can leverage within your application.
You just need to tell Java that you are going to use them by
importing them via the Java import command.
Android TextView
0 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
android:id This is the ID which uniquely identifies the control.
android:gravity Specifies how to align the text by the view's x-
and/or y-axis when the text is smaller than the view.
android:maxHeight Makes the TextView be at most this many pixels
tall.
android:maxWidth Makes the TextView be at most this many pixels
wide.
android:minHeight Makes the TextView be at least this many pixels
tall.
android:minWidth Makes the TextView be at least this many pixels
wide.
Cont…
android:text Text to display.
android:textAllCaps Present the text in ALL CAPS. Possible value
either "true" or "false".
android:textColor Text color. May be a color value, in the form of
"#rgb", "#argb", "#rrggbb", or "#aarrggbb".
android:textColorHighlight Color of the text selection highlight.
android:textColorHint Color of the hint text. May be a color value,
in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".
android:textIsSelectable Indicates that the content of a non-
editable text can be selected. Possible value either "true" or "false".
android:textSize Size of the text. Recommended dimension type
for text is "sp" for scaled-pixels (example: 15sp).
Sample Android application using Relative Layout
and TextView.
0 Following will be the content of res/layout/activity_main.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/text_id"
android:layout_width="wrap_content" android:layout_height="wrap_content"

android:capitalize="characters"
android:text="@string/hello_world" />
</RelativeLayout>
0 Following is the content of the modifid main activity file
src/com.example.guidemo/MainActivity.java. This file can include each of the
fundamental lifecycle methods.
package com.example.guidemo;
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);
final String Label = txtView.getText().toString();
txtView.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(getApplicationContext(),
"You have clicked the Label : " + Label,
Toast.LENGTH_LONG).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true; } }
0 Let's try to run your application. I assume you had created
your AVD while doing environment setup. It will look like the
ff Emulator window:
Android EditText
0 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.
EditText Attributes
Following are the important attributes related to EditText control.
Inherited from android.widget.TextView Class:
android:autoText If set, specifies that this TextView has a textual
input method and automatically corrects some common spelling errors.
android:drawableBottom This is the drawable to be drawn below the
text.
android:drawableRight This is the drawable to be drawn to the right
of the text.
android:editable If set, specifies that this TextView has an input
method.
android:text This is the Text to display
Cont…
android:background
This is a drawable to use as the background.
android:contentDescription
This defines text that briefly describes content of the view.
android:id
This supplies an identifier name for this view,
android:onClick
This is the name of the method in this View's context to invoke
when the view is clicked.
android:visibility
This controls the initial visibility of the view.
Android application using Relative Layout and
EditText.
<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="com.example.hello2.MainActivity" >

<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_centerHorizontal="true"
android:ems="10"
android:text="@string/show_the_text" />
<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="104dp"
android:text="@string/enter_text" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:text="@string/example_edittext" />
</RelativeLayout>
Cont…
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">Hello2</string>
<string name="hello_world">Hello world!</string>
<string name="show_the_text">Show Text</string>
<string name="example_edittext">Example Showing
EditText</string>
<string name="enter_text">Text changes</string>
<string name="action_settings">Settings</string>
</resources>
Cont…
package com.example.hello4;

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.textView1);
final String Label = txtView.getText().toString();
txtView.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {


// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"You have clicked the Label : " + Label,
Toast.LENGTH_LONG).show();

}
});
}

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

}
0 Let's try to run your application. I assume you had created
your AVD while doing environment setup. It will look like the
ff Emulator window:
AutoCompleteTextView
0 A AutoCompleteTextView is a view that is similar to EditText, except
that it shows a list of completion suggestions automatically while the
user is typing. The list of suggestions is displayed in drop down menu.
AutoCompleteTextView Attributes
android:completionHint This defines the hint displayed in the drop
down menu.
android:completionHintView This defines the hint view displayed in
the drop down menu.
android:completionThreshold
This defines the number of characters that the user must type before
completion suggestions are displayed in a drop down menu.
android:dropDownAnchor This is the View to anchor the
auto-complete dropdown to.
android:dropDownHeight This specifies the basic height of
the dropdown.
android:dropDownHorizontalOffset The amount of pixels
by which the drop down should be offset horizontally.
android:dropDownSelector This is the selector in a drop
down list.
android:dropDownVerticalOffset The amount of pixels by
which the drop down should be offset vertically.
android:dropDownWidth This specifies the basic width of
the dropdown.
android:popupBackground This sets the background.
Android application using Relative Layout and
AutoCompleteTextView.
0Following 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="com.example.hello2.MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/autoCompleteTextView1"
android:layout_alignParentTop="true"
android:layout_marginTop="84dp"
android:text="@string/example_aoutocompletetextview" />
<AutoCompleteTextView
android:id="@+id/autoCompleteTextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:ems="10"
/>

</RelativeLayout>
0 Following is the content of the modified main activity
filesrc/com.example.guidemo3/MainActivity.java.
package com.example.guidemo3;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
public class MainActivity extends Activity
{ AutoCompleteTextView autocompletetextview;
String[] arr = { "MS SQL SERVER", "MySQL", "Oracle" };
@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
autocompletetextview = (AutoCompleteTextView)
findViewById(R.id.autoCompleteTextView1);
ArrayAdapter adapter = new ArrayAdapter
(this,android.R.layout.select_dialog_item, arr);
autocompletetextview.setThreshold(1);
autocompletetextview.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
/* Inflate the menu; this adds items to the action bar if it is
present */
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
0 Let's try to run your application. I assume you had created
your AVD while doing environment setup. It will look like the
ff Emulator window:
Android Button
0 A Button is a Push-button which can be pressed, or clicked, by the
user to perform an action.
Button Attributes
Inherited from android.widget.TextView Class:
android:autoText
If set, specifies that this TextView has a textual input method and
automatically corrects some common spelling errors.
android:drawableBottom This is the drawable to be drawn below the
text.
android:drawableRight This is the drawable to be drawn to the right
of the text.
android:editable If set, specifies that this TextView has an input
method.
android:text This is the Text to display.
0 Inherited from android.view.View Class:
android:background This is a drawable to use as the
background.
android:contentDescription This defines text that briefly
describes content of the view.
android:id This supplies an identifier name for this view,
android:onClick
This is the name of the method in this View's context to
invoke when the view is clicked.
android:visibility This controls the initial visibility of the
view.
0 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="@string/example_button" />
<EditText
android:id="@+id/edittext"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/textView1"
android:layout_marginTop="61dp"
android:ems="10"
android:inputType="text"
android:text="@string/enter_text1" />
<EditText
android:id="@+id/edittext2"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:layout_alignLeft="@+id/edittext3"
android:layout_below="@+id/edittext" android:layout_marginTop="17dp"

android:ems="10"
android:inputType="text"
android:text="@string/enter_text2" />
<EditText
android:id="@+id/edittext3" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/edittext"
android:layout_below="@+id/edittext2"
android:layout_marginTop="14dp"
android:ems="10"
android:inputType="text"
android:text="@string/enter_text3" />
<Button
android:id="@+id/button1" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/edittext3"
android:layout_marginTop="35dp"
android:text="@string/click_button" />
</RelativeLayout>
0 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">GUIDemo4</string>
<string name="action_settings">Settings</string>
<string name="example_button">Example showing
Button</string>
<string name="enter_text1"/> </string>
<string name="enter_text2"/> </string>
<string name="enter_text3"/> </string>
<string name="click_button">Calculate product of 3
numbers</string>
</resources
package com.example.guidemo4;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
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 {
private EditText edText1,edText2,edText3;
private Button btnProduct;
@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton(); }
private void addListenerOnButton() {
edText1 = (EditText)findViewById(R.id.edittext);
edText2 = (EditText)findViewById(R.id.edittext2);
edText3 = (EditText)findViewById(R.id.edittext3);
btnProduct = (Button)findViewById(R.id.button1);
btnProduct.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
String t1 = edText1.getText().toString();
String t2 = edText2.getText().toString();
String t3 = edText3.getText().toString();
int i1 = Integer.parseInt(t1);
int i2 = Integer.parseInt(t2);
int i3 = Integer.parseInt(t3);
int product = i1*i2*i3;
Toast.makeText(getApplicationContext(),
String.valueOf(product),Toast.LENGTH_LONG).show();
} }); }
@Override
public boolean onCreateOptionsMenu(Menu menu) {
/* Inflate the menu; this adds items to the action bar if it
is present */
getMenuInflater().inflate(R.menu.main, menu);
return true; } }
Let's try to run your application. I assume you had created
your AVD while doing environment setup. It will look like
the ff Emulator window:
Android CheckBox
A CheckBox is an on/off switch that can be toggled by the user.
You should use check-boxes when presenting users with a
group of selectable options that are not mutually exclusive.
CheckBox Attributes
Inherited from android.widget.TextView Class:
android:autoText
If set, specifies that this TextView has a textual input method
and automatically corrects some common spelling errors.
android:drawableBottom This is the drawable to be drawn
below the text.
android:drawableRight This is the drawable to be drawn to the
right of the text.
android:editable If set, specifies that this TextView has an input
method.
android:text This is the Text to display.
Inherited from android.view.View Class:
android:background This is a drawable to use as the
background.
android:contentDescription This defines text that briefly
describes content of the view.
android:id This supplies an identifier name for this view,
android:onClick
This is the name of the method in this View's context to invoke
when the view is clicked.
android:visibility This controls the initial visibility of the view
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/androi
d" 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="@string/example_checkbox" />
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="88dp"
android:text="@string/check_one" />
<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/checkBox1"
android:layout_below="@+id/checkBox1"
android:layout_marginTop="22dp"
android:text="@string/check_two" />
<CheckBox
android:id="@+id/checkBox3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/checkBox2"
android:layout_marginTop="24dp"
android:text="@string/check_three" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/checkBox1"
android:layout_below="@+id/textView1"
android:layout_marginTop="39dp"
android:text="@string/example_question" />
</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">GUIDemo6</string>
<string name="action_settings">Settings</string>
<string name="example_checkbox">Example showing
CheckBox Control</string>
<string name="check_one">JAVA</string>
<string name="check_two">PERL</string>
<string name="check_three">PYTHON</string>
<string name="example_question">Worked on following
Languages-</string>
</resources>
0 Following is the content of the modified main activity
filesrc/com.example.guidemo5/MainActivity.java
package com.example.guidemo6;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.Toast;
public class MainActivity extends Activity {
private CheckBox chk1, chk2, chk3;
@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);

// 3 methods
addListenerOnCheck1();
addListenerOnCheck2();
addListenerOnCheck3();
}
// method for CheckBox1 - Java
private void addListenerOnCheck1() {
chk1 = (CheckBox) findViewById(R.id.checkBox1);
chk2 = (CheckBox) findViewById(R.id.checkBox2);
chk3 = (CheckBox) findViewById(R.id.checkBox3); chk2.setOnClickListener(new
OnClickListener() {
@Override
public void onClick(View v) {
StringBuffer result = new StringBuffer();
result.append("Java Selection : ").append (chk1.isChecked());
result.append("\nPerl Selection : ").append (chk2.isChecked());
result.append("\nPython Selection :").append (chk3.isChecked());
Toast.makeText(MainActivity.this, result.toString(),
Toast.LENGTH_LONG).show();
} });
}
// method for CheckBox2 - Perl
private void addListenerOnCheck2() {
private void addListenerOnCheck2() {
chk1 = (CheckBox) findViewById(R.id.checkBox1);
chk2 = (CheckBox) findViewById(R.id.checkBox2);
chk3 = (CheckBox) findViewById(R.id.checkBox3);
chk3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
StringBuffer result = new StringBuffer();
result.append("Java Selection : ").append (chk1.isChecked());
result.append("\nPerl Selection : ").append (chk2.isChecked());
result.append("\nPython Selection :").append (chk3.isChecked());
Toast.makeText(MainActivity.this, result.toString
(),Toast.LENGTH_LONG).show();
}
});
}
/* method for CheckBox3 - Python */
private void addListenerOnCheck3() { // TODO Auto-generated method stub
chk1 = (CheckBox) findViewById(R.id.checkBox1);
chk2 = (CheckBox) findViewById(R.id.checkBox2);
chk3 = (CheckBox) findViewById(R.id.checkBox3); chk1.setOnClickListener(new
OnClickListener()
{ @Override
public void onClick(View v)
{
StringBuffer result = new StringBuffer();
result.append("Java Selection : ").append(chk1.isChecked());
result.append("\nPerl Selection : ").append(chk2.isChecked());
result.append("\nPython Selection :").append(chk3.isChecked());
Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();
} }); }
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
0 Let's try to run your application. I assume you had created
your AVD while doing environment setup. It will look like the
ff Emulator window:
Android AlertDialog
0 Android AlertDialog can be used to display the dialog mes
sage with
OK and Cancel buttons. It can be used to interrupt and ask 
the user about his/her choice to continue or discontinue.
0 Android AlertDialog is composed of three regions: title, co
ntent area and action buttons.
0 Android AlertDialog is the subclass of Dialog class.
0 Android AlertDialog Example
activity_main.xml
Activity_main.xml file

<RelativeLayout 
xmlns:androclass="http://schemas.android.com/apk/res/android" xmlns:tools="ht
tp://schemas.android.com/tools"     
  android:layout_width="match_parent"       
android:layout_height="match_parent"      
 tools:context=".MainActivity" >          
<TextView          
 android:layout_width="wrap_content"           
android:layout_height="wrap_content"           
android:layout_centerHorizontal="true"           
android:layout_centerVertical="true"          
 android:text="@string/hello_world" />     
</RelativeLayout>  
File: strings.xml
<?xml version="1.0" encoding="utf­8"?>  
<resources>          
<string name="app_name">alertdialog</string>       
<string name="hello_world">Hello world!</string>       
<string name="menu_settings">Settings</string>       
<string name="dialog_message">Welcome to Alert Dialog</stri
ng>          
<string name="dialog_title">Javatpoint Alert Dialog</string>  
</resources>  
0 MainActivit.java file
package com.example.hello2;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//Uncomment the below code to Set the message and title from the strings.xml file  
/
*builder.setMessage(R.string.dialog_message).setTitle(R.string.dialog_title).setCancel
able(false).setPositiveButton("Close", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
finish();
}
}).setNegativeButton("Back", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();

}
}); */
//setting message manually and performing action on button click
builder.setMessage("do you want to close this
application?").setCancelable(false).setPositiveButton("Yes", new
DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {

finish();
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {

//Action for No Button


dialog.cancel();
}
});
//creating dialog box
AlertDialog alert= builder.create();
//setting the title manually
alert.setTitle("AlertDialog Example");
alert.show();
setContentView(R.layout.activity_main);
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
0 The above application code will look like the following
when you run using emulator.
Android Layouts
Linear Layouts
0 It is designed to contain and arrange UI elements placed inside
it across the screen (using the horizontal orientation
parameter) or up and down the screen (using the vertical
orientation parameter).
0 Here's the attribute for orientation in the LinearLayout tag for
XML:
<LinearLayout android:orientation="vertical">
here’s how it’s normally coded:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
Cont…
0 The first parameter of the LinearLayout XML tag is the path to
the Android XML schema definition.
0 android:orientation="vertical“ : This sets all the items in
the linearLayout vertically.
0 The value for the layout width and height parameters,
fill_parent, simply tells the LinearLayout to expand to fill its
parent container. Since this is the top level LinearLayout
container, that would mean to fill the smartphone display
screen.
0 If the layout orientation is horizontal anything we place inside
this container will display across the screen from left to right
Cont…
0 Under TextView tag
android:layout_width="fill_parent" means the text referenced
by string hello fills its parent width therefore the layouts
width.
fill_parent is the same with “match_parent” in API level 8 and
higher.
android:layout_height="wrap_content“ means the text wrap
or big enough up to the height of its content(the text) only.
android:text="@string/hello" : @ here means is a reference
which is referencing the string hello . Hello is the name of the
reference but displaying text is Hellow_world(value for the
reference).
You can create new reference in Values->String.xml->Add
0 More Example on LinearLayout
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"

android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
android:background="#fbfbfb">

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/res"
/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/vertical"
/>

</LinearLayout>  
Relative Layouts
o The RelativeLayout layout class allows you to define how the UI
elements (the View objects) are to be placed on the screen relative to
each other, rather than just laid out linearly.
o RelativeLayout container allows you to arrange all sorts of UI
elements together in a single ViewGroup to achieve a complex layout.
o Defining ID for View objects is important when creating Relative
Layout. In RelativeLayout sibling views can define their layout
relative to another sibling view, which is referenced by the unique
ID.

Here is example:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Type here:"/>
<EditText
android:id="@+id/entry"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/label" />
<Button
android:id="@+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/entry"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dip"
android:text="OK"/>
<Button
android:id="@+id/cancel" android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:layout_toLeftOf="@+id/ok"
android:layout_alignTop="@+id/ok"
android:text="Cancel"/>
</RelativeLayout>
Following will be the content of src/MainActivity.java  file 

package com.example.helloworld;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{ getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
 TableLayout 
0 Android TableLayout going to be arranged groups of views into rows and columns. 
0 You will use the TableRow element to build a row in the
table. Each row has zero or more cells each cell can hold one View object.
0 TableLayout containers do not display border lines for their rows, columns, or cells.

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

android:collapseColumns
This specifies the zero­based index of the columns to collapse. The column
indices must be separated by a comma: 1, 2, 5.

android:stretchColumns
The zero­based index of the columns to stretch. The column indices must
be separated by a comma: 1, 2, 5.
0 Following will be the content of res/layout/activity_main.xml file 
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity" >

<TableRow
android:paddingTop="10dp"
android:gravity="center">

<TextView
android:id="@+id/status"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:layout_span="2"
android:text="@string/Login"
android:textColor="#890000"
android:textSize="15sp"
android:textStyle="bold" > </TextView>
</TableRow>
<TableRow android:layout_marginTop="20dip" >
<TextView
android:layout_width="wrap_content"
android:text="@string/Username"
android:textSize="20sp"
android:textColor="#000000"
android:layout_marginLeft="20dip"
>
</TextView>
<EditText
android:id="@+id/screenName"
android:layout_height="wrap_content"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:layout_weight="1" ></EditText> </TableRow>
<TableRow android:layout_marginTop="20dip" >

<TextView
android:text="@string/Password"
android:layout_width="wrap_content"
android:textSize="20sp"
android:textColor="#000000"
android:layout_height="wrap_content"
android:layout_marginLeft="20dip"></TextView>

<EditText
android:id="@+id/password"
android:layout_height="wrap_content"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:layout_weight="1" >
</EditText></TableRow>
<TableRow android:gravity="center"
android:layout_marginTop="20dip" >

<Button
android:text="@string/Submit"
android:clickable="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/save"
android:layout_span="2" >
</Button>
</TableRow>
</TableLayout>
Table Layout Cont…
Following will be the content of res/layout/activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">WowChalenge</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="Username">Username :</string>
<string name="Password">Password :</string>
<string name="Submit">Submit</string>
<string name="Login">LOGIN</string
</resources>
0 The previous code of Table Layout will look like the
following image on the emulator.
 Absolute Layout
0 An Absolute Layout lets you specify exact locations (x/y coordinat
es) ofits children. Absolute layouts are less flexible and harder to 
maintain than other types of layouts without absolute positioning.
0 ABSOLUTE LAYOUT AbsoluteLayout Attributes
android:id
This is the ID which uniquely identifies the layout.
android:layout_x
This specifies the x­coordinate of the view.
android:layout_y
This specifies the y­coordinate of the view.
 Absolute Layout cont…
0 Following will be the content of res/layout/activity_main.xml file −
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"    
android:layout_width="fill_parent"    
android:layout_height="fill_parent">        
<Button       
android:layout_width="100dp"       
android:layout_height="wrap_content"       
android:text="OK"       
android:layout_x="50px"      
 android:layout_y="361px" />    
<Button       
android:layout_width="100dp"       
android:layout_height="wrap_content"      
 android:text="Cancel"      
 android:layout_x="225px"      
 android:layout_y="361px" />
0 </AbsoluteLayout>
 Absolute Layout Cont…
0 Following  is  the  content  of  the  modified  main  activity  file
src/com.example.demo/MainActivity.java. 
package com.example.demo;
import android.os.Bundle;
import android.app.Activity;
public class MainActivity extends Activity {    
@Override    
protected void onCreate(Bundle savedInstanceState) 
{      
 super.onCreate(savedInstanceState);      
 setContentView(R.layout.activity_main);   
 }  
   }
Building Layouts with an Adapter
0 If you want the user to choose something out of a collection of
somethings(like RadioButton widgets) and when the content of
your layout is dynamic, you can use a layout that subclasses
AdapterView to populate the layout with views at run time.

0 An AdapterView is a ViewGroup that gets its child views from


an Adapter. A subclass of the Adapter View class uses an Adapter
by building the AdapterView instance to an Adapter.

0 An Adapter is responsible for creating and binding data to views.


An Adapter isn't an actual view, but instead produces them.
0 The adapter behaves as a middleman between the data source and the layout . The
Adapter retrieves the data ( from the source such as an array or a data base query)
and converts each entry into a view that can be added to the AdapterView layout.

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

0 Example of subclasses of AdapterView class


0 ListView
0 Spinner
0 GridView
0 ExpandableListView
a limited “tree” widget, supporting two levels in the hierarchy
0 Gallary
a horizontal-scrolling list, principally used for image thumbnails
Adapter
0 Android provides several subclasses of Adapter that are useful for
retrieving different kinds of data and building views for Anadapter
view.
ArrayAdapter
0 Use this adapter when your data source id array. By default
ArrayAdapter creates a view for each array item by calling toString ()
and placing the content view in a TextView.
0 For example if you have an array of string you want it display in a
ListView.
0 Initialize a new Array Adapter using a constructor to specify the
layout for each string and the string array.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,
myStringArray);
0 The arguments for this constructor are
0 Your app context
0 The layout that contains a TextView for each string in the array
0 The string array
0 Then simply call setAdapter
ListView listView;
listView.setAdapter(adapter);
SimpleCursorAdapter
use this adapter when your data comes from a cursor. You must specify a
layout for each row in the cursor and which columns in the cursor
inserted into which views of the layout.
String[] fromColumns = {ContactsContract.Data.DISPLAY_NAME,
                        ContactsContract.CommonDataKinds.Phone.NUMBER};
int[] toViews = {R.id.display_name, R.id.phone_number};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,        
 R.layout.person_name_and_number, cursor, fromColumns, toViews, 0);
ListView listView = getListView(); listView.setAdapter(adapter);
Handling click events
listView.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {

// do some thing in response to the click.

});
Android ListView
0 which is your typical “list box”
0 Following will be the content of res/layout/activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

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

</LinearLayout>
0 Following will be the content of src/MainActivity.java
package com.example.wowchalenge;import
android.os.Bundle;import android.app.Activity;import
android.view.Menu;import android.view.View;import
android.widget.AdapterView;import
android.widget.AdapterView.OnItemClickListener;import
android.widget.ArrayAdapter;import
android.widget.ListView;import android.widget.Toast;public
class MainActivity extends Activity {
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView =(ListView) findViewById(R.id.list};
);
// Defined Array values to show in ListView
String[] values = new String[] {
"Android List View",
"Adapter implementation",
"Simple List View In Android",
"Create List View Android",
"Android Example",
"List View Source Code",
"List View Array Adapter",
"Android Example List View“
// Define a new Adapter
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is
//written
// Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
// ListView Item Click Listener
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue =(String)listView.getItemAtPosition(position);
// Show Alert
Toast.makeText(getApplicationContext(),
"Position :"+itemPosition+" ListItem : " +itemValue ,
Toast.LENGTH_LONG) .show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
0 Android code of the list view demo in the above slides
will have the following dispay on the emulator.
Android Grid  View
0 Android GridView shows items in two­
dimensional scrolling grid (rows &
columns) and the grid items are not necessarily prede
termined but they
automatically inserted to the layout using a List
Adapter.
GridView Attributes
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.
Following are the important attributes specific to GridView −
Sr.No Attribute & Description

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

android:columnWidth
This specifies the fixed width for each column. This could be in px, dp, sp,
in, or mm.
android:gravity
Specifies the gravity within each cell. Possible values are top, bottom, 
left, right, center, center_vertical, center_horizontal etc.

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

android:numColumns
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 t
o fill the available space.
<GridLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android1="http://schemas.android.com/apk/res/android"
android:id="@+id/GridLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:columnCount="3"
android:orientation="horizontal"
android:rowCount="3"
tools:context="com.inducesmile.gridlayouttutorial.MainActivity" >

<Button
android:id="@+id/button1"
android:layout_gravity="left|top"
android:text="@string/btn1" />

<Button
android:id="@+id/button3"
android:layout_gravity="left|top"
android:text="@string/btn2" />

<Button
android:id="@+id/button2"
android:layout_column="0"
android:layout_gravity="left|top"
android:layout_row="0"
android:text="@string/btn3" />

<Button
android:id="@+id/button4"
android:layout_column="0"
android:layout_gravity="left|top"
android:layout_row="2"
android:text="@string/btn4" />

<Button
android:id="@+id/button5"
android:layout_column="1"
android:layout_row="2"
android:layout_columnSpan="2"
android:layout_gravity="fill"
android:text="@string/btn5" />

</GridLayout>

You might also like