Unit Iv
Unit Iv
4.1.1 TextView:
A TextView displays text to the user and optionally allows them to edit it. A TextView
is a complete text editor, however the basic class is configured to not allow editing.
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.
3 android:cursorVisible
Makes the cursor visible (the default) or invisible. Default is false.
4 android:editable
If set to true, specifies that this TextView has an input method.
5 android:fontFamily
Font family (named by string) for the text.
6 android:gravity
Specifies how to align the text by the view's x- and/or y-axis when the text
is smaller than the view.
7 android:hint
Hint text to display when the text is empty.
8 android:inputType
The type of data being placed in a text field. Phone, Date, Time, Number,
Password etc.
9 android:maxHeight
Makes the TextView be at most this many pixels tall.
10 android:maxWidth
Makes the TextView be at most this many pixels wide.
11 android:minHeight
Makes the TextView be at least this many pixels tall.
12 android:minWidth
Makes the TextView be at least this many pixels wide.
13 android:password
Whether the characters of the field are displayed as password dots instead
of themselves. Possible value either "true" or "false".
14 android:phoneNumber
If set, specifies that this TextView has a phone number input method.
Possible value either "true" or "false".
15 android:text
Text to display.
16 android:textAllCaps
Present the text in ALL CAPS. Possible value either "true" or "false".
17 android:textColor
Text color. May be a color value, in the form of "#rgb", "#argb", "#rrggbb",
or "#aarrggbb".
18 android:textColorHighlight
Color of the text selection highlight.
19 android:textColorHint
Color of the hint text. May be a color value, in the form of "#rgb", "#argb",
"#rrggbb", or "#aarrggbb".
20 android:textIsSelectable
Indicates that the content of a non-editable text can be selected. Possible
value either "true" or "false".
21 android:textSize
Size of the text. Recommended dimension type for text is "sp" for scaled-
pixels (example: 15sp).
22 android:textStyle
Style (bold, italic, bolditalic) for the text. You can use or more of the
following values separated by '|'.
normal - 0
bold - 1
italic - 2
23 android:typeface
Typeface (normal, sans, serif, monospace) for the text. You can use or
more of the following values separated by '|'.
normal - 0
sans - 1
serif - 2
monospace - 3
Example
This example will take you through simple steps to show how to create your
own Android application using Linear Layout and TextView.
Step Description
1 You will use Android studio to create an Android application and name it
as demo under a package com.example.demo as explained in the Hello
World Example chapter.
5 Run the application to launch Android emulator and verify the result of the
changes done in the application.
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
<TextView
android:id="@+id/text_id"
android:layout_width="300dp"
android:layout_height="200dp"
android:capitalize="characters"
android:text="hello_world"
android:textColor="@android:color/holo_blue_dark"
android:textColorHighlight="@android:color/primary_text_dark"
android:layout_centerVertical="true"
android:layout_alignParentEnd="true"
android:textSize="50dp"/>
</RelativeLayout>
Following will be the content of res/values/strings.xml to define two new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">demo</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.demo" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.demo.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your demo application. I assume you had created
your AVD while doing environment setup. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Android studio installs the app on your AVD and starts it and if everything is
fine with your setup and application, it will display following Emulator window −
4.1.2 EditText:
A EditText is an overlay over TextView that configures itself to be editable. It is
the predefined subclass of TextView that includes rich editing capabilities.
Styles of edit text
1 android:autoText
If set, specifies that this TextView has a textual input method and
automatically corrects some common spelling errors.
2 android:drawableBottom
This is the drawable to be drawn below the text.
3 android:drawableRight
This is the drawable to be drawn to the right of the text.
4 android:editable
If set, specifies that this TextView has an input method.
5 android:text
This is the Text to display.
Inherited from android.view.View Class −
Sr.N Attribute & Description
o
1 android:background
This is a drawable to use as the background.
2 android:contentDescription
This defines text that briefly describes content of the view.
3 android:id
This supplies an identifier name for this view.
4 android:onClick
This is the name of the method in this View's context to invoke when the view
is clicked.
5 android:visibility
Example
This example will take you through simple steps to show how to create your own
Android application using Linear Layout and EditText.
Step Description
1 You will use Android studio IDE to create an Android application and name it
as demo under a package com.example.demo as explained in the Hello World
Example chapter.
5 Run the application to launch Android emulator and verify the result of the
changes done in the application.
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;
<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 –
1 android:completionHint
This defines the hint displayed in the drop down menu.
android:completionHintView
2
This defines the hint view displayed in the drop down menu.
android:completionThreshold
3 This defines the number of characters that the user must type before
completion suggestions are displayed in a drop down menu.
android:dropDownAnchor
4
This is the View to anchor the auto-complete dropdown to.
android:dropDownHeight
5
This specifies the basic height of the dropdown.
android:dropDownHorizontalOffset
6 The amount of pixels by which the drop down should be offset
horizontally.
android:dropDownSelector
7
This is the selector in a drop down list.
android:dropDownVerticalOffset
8
The amount of pixels by which the drop down should be offset vertically.
android:dropDownWidth
9
This specifies the basic width of the dropdown.
android:popupBackground
10
This sets the background.
Example
This example will take you through simple steps to show how to create your
own Android application using Linear Layout and AutoCompleteTextView.
Ste Description
p
1 You will use Android Studio IDE to create an Android application and name
it as GUIDemo3 under a package com.example.guidemo3 as explained in
the Hello World Example chapter.
5 Run the application to launch Android emulator and verify the result of the
changes done in the application.
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
autocomplete = (AutoCompleteTextView)
findViewById(R.id.autoCompleteTextView1);
autocomplete.setThreshold(2);
autocomplete.setAdapter(adapter);
}
}
Following will be the content of res/layout/activity_main.xml file −
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:text="@string/example_autocompletetextview" />
<AutoCompleteTextView
android:id="@+id/autoCompleteTextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"
android:layout_below="@+id/textView2"
android:layout_marginTop="54dp"
android:ems="10" />
</RelativeLayout>
Following will be the content of res/values/strings.xml to define these new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">GUIDemo3</string>
<string name="example_autocompletetextview">Example
showing AutoCompleteTextView</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.guidemo3" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.guidemo3.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your GUIDemo3 application. I assume you had created
your AVD while doing environment setup. To run the app from Android Studio,
open one of your project's activity files and click Run icon from the toolbar.
Android Studio installs the app on your AVD and starts it and if everything is
fine with your setup and application, it will display following Emulator window −
The following screen will appear after "pa" will be typed in
AutoCompleteTextView −
4.1.4 Button:
A Button is a Push-button which can be pressed, or clicked, by the user to
perform an action.
4.1.4(A) Button Attributes:
Following are the important attributes related to Button control. You can check
Android official documentation for complete list of attributes and related
methods which you can use to change these attributes are run time.
Inherited from android.widget.TextView Class −
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.
Attribute Description
1 android:background
This is a drawable to use as the background.
2 android:contentDescription
This defines text that briefly describes content of the view.
3 android:id
This supplies an identifier name for this view.
4 android:onClick
This is the name of the method in this View's context to invoke
when the view is clicked.
5 android:visibility
This controls the initial visibility of the view.
Example
This example will take you through simple steps to show how to create your
own Android application using Linear Layout and Button.
Step Description
1 You will use Android studio IDE to create an Android application and name it
as myapplication under a package com.example.saira_000.myapplication as
explained in the Hello World Example chapter.
Run the application to launch Android emulator and verify the result of the
5
changes done in the application.
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"YOUR
MESSAGE",Toast.LENGTH_LONG).show();
}
});
}
}
Following will be the content of res/layout/activity_main.xml file −
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button Control"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/imageButton"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:id="@+id/button"
android:layout_alignTop="@+id/editText"
android:layout_alignLeft="@+id/textView1"
android:layout_alignStart="@+id/textView1"
android:layout_alignRight="@+id/editText"
android:layout_alignEnd="@+id/editText" />
</RelativeLayout>
Following will be the content of res/values/strings.xml to define these new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">myapplication</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.saira_000.myapplication" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.guidemo4.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your GUIDemo4 application. I assume you had created
your AVD while doing environment setup. To run the app from Android Studio,
open one of your project's activity files and click Run icon from the
toolbar.Android Studio installs the app on your AVD and starts it and if
everything is fine with your setup and application, it will display following
Emulator window −
Androi
d button style set
android:adjustViewBounds
1
Set this to true if you want the ImageView to adjust its bounds to preserve the
aspect ratio of its drawable.
2 android:baseline
This is the offset of the baseline within this view.
3 android:baselineAlignBottom
If true, the image view will be baseline aligned with based on its bottom edge.
4 android:cropToPadding
If true, the image will be cropped to fit within its padding.
5 android:src
This sets a drawable as the content of this ImageView.
1 android:background
This is a drawable to use as the background.
2 android:contentDescription
This defines text that briefly describes content of the view.
3 android:id
This supplies an identifier name for this view
4 android:onClick
This is the name of the method in this View's context to invoke when the view
is clicked.
5 android:visibility
This controls the initial visibility of the view.
Example
This example will take you through simple steps to show how to create your
own Android application using Linear Layout and ImageButton.
Step Description
1 You will use Android studio IDE to create an Android application and name it
as myapplication under a package com.example.myapplication as explained in
the Hello World Example chapter.
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;
</RelativeLayout>
Following will be the content of res/values/strings.xml to define these new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">myapplication</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.myapplication.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your myapplication application. I assume you had created
your AVD while doing environment setup. To run the app from Android Studio,
open one of your project's activity files and click Run icon from the toolbar.
Android Studio installs the app on your AVD and starts it and if everything is
fine with your setup and application, it will display following Emulator window −
The following screen will appear after ImageButton is clicked,It shows a toast
message.
4.1.6 Toggle Button:
A ToggleButton displays checked/unchecked states as a button. It is basically
an on/off button with a light indicator.
Toggle Button
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.
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.
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.
4 Run the application to launch Android emulator and verify the result of the
changes done in the application.
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;
If you have clicked first on Button, you would get a message on Toast as You
have clicked first ON Button-:) or else if you clicked on second on button,
you would get a message on Toast as You have clicked Second ON Button
-:)
4.1.7 Radio Button:
A RadioButton has two states: either checked or unchecked.This allows the
user to select one option from a set.
Radio Button
Example
This example will take you through simple steps to show how to create your
own Android application using Linear Layout and RadioButton.
Step Description
1 You will use Android studio to create an Android application and name it as My
Application under a package com.example.saira_000.myapplication as
explained in the Hello World Example chapter.
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;
</activity>
</application>
</manifest>
Let's try to run your My Application application. I assume you had created
your AVD while doing environment setup. To run the app from Android Studio,
open one of your project's activity files and click Run icon from the toolbar.
Android Studio installs the app on your AVD and starts it and if everything is
fine with your setup and application, it will display following Emulator window −
If User selected any of a Radio Button, It should give same name on Toast
message. for suppose, if User selected JAVA, it gives a toast message as
JAVA
Attribute Description
1 android:background
This is a drawable to use as the background.
2 android:contentDescription
This defines text that briefly describes content of the view.
3 android:id
This supplies an identifier name for this view
4 android:onClick
This is the name of the method in this View's context to invoke when the view
is clicked.
5 android:visibility
This controls the initial visibility of the view.
Example
This example will take you through simple steps to show how to create your
own Android application using Linear Layout and RadioGroup.
Step Description
1 You will use Android studio IDE to create an Android application and name it
as My Application under a package com.example.saira_000.myapplication; as
explained in the Hello World Example chapter.
4 Run the application to launch Android emulator and verify the result of the
changes done in the application.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioSexGroup=(RadioGroup)findViewById(R.id.radioGroup);
btnDisplay=(Button)findViewById(R.id.button);
btnDisplay.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
int
selectedId=radioSexGroup.getCheckedRadioButtonId();
radioSexButton=(RadioButton)findViewById(selectedId);
Toast.makeText(MainActivity.this,radioSexButton.getText(),Toa
st.LENGTH_SHORT).show();
}
});
}
}
Following will be the content of res/layout/activity_main.xml file −
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Radio button"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="35dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorialspoint"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView"
android:textSize="35dp"
android:textColor="@android:color/holo_green_dark" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_alignLeft="@+id/textView"
android:layout_alignStart="@+id/textView"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView" />
<RadioGroup
android:layout_width="fill_parent"
android:layout_height="90dp"
android:layout_below="@+id/imageView"
android:layout_marginTop="58dp"
android:weightSum="1"
android:id="@+id/radioGroup"
android:layout_alignLeft="@+id/textView2"
android:layout_alignStart="@+id/textView2"
android:layout_alignRight="@+id/textView3"
android:layout_alignEnd="@+id/textView3">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="55dp"
android:text="Male"
android:id="@+id/radioButton"
android:layout_gravity="center_horizontal"
android:checked="false"
android:textSize="25dp" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:id="@+id/radioButton2"
android:layout_gravity="center_horizontal"
android:checked="false"
android:textSize="25dp"
android:layout_weight="0.13" />
</RadioGroup>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Are you?"
android:id="@+id/textView3"
android:textSize="35dp"
android:layout_below="@+id/imageView"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button"
android:layout_gravity="center_horizontal"
android:layout_below="@+id/radioGroup"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Following will be the content of res/values/strings.xml to define these new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My Applicaiton</string>
<string name="example_radiogroup">Example showing
RadioGroup</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.saira_000.myapplication" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.My
Application.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your My Application application. I assume you had created
your AVD while doing environment setup. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Android studio installs the app on your AVD and starts it and if everything is
fine with your setup and application, it will display following Emulator window −
The following screen will appear, here we have a RadioGroup.
Need to select male or female radio button then click on new button. if you do
above steps without fail, you would get a toast message after clicked by new
button
4.1.9 CheckBox:
A CheckBox is an on/off switch that can be toggled by the user. You should
use check-boxes when presenting users with a group of selectable options that
are not mutually exclusive.
CheckBox
4.1.9(A) CheckBox Attributes:
Following are the important attributes related to CheckBox control. You can
check Android official documentation for complete list of attributes and related
methods which you can use to change these attributes are run time.
Inherited from android.widget.TextView Class −
android:autoText
1
If set, specifies that this TextView has a textual input method and automatically
corrects some common spelling errors.
2 android:drawableBottom
This is the drawable to be drawn below the text.
3 android:drawableRight
This is the drawable to be drawn to the right of the text.
4 android:editable
If set, specifies that this TextView has an input method.
5 android:text
This is the Text to display.
1 android:background
This is a drawable to use as the background.
2 android:contentDescription
This defines text that briefly describes content of the view.
3 android:id
This supplies an identifier name for this view.
android:onClick
4
This is the name of the method in this View's context to invoke when the view
is clicked.
5 android:visibility
This controls the initial visibility of the view.
Example
This example will take you through simple steps to show how to create your
own Android application using Linear Layout and CheckBox.
Step Description
1 You will use Android Studio IDE to create an Android application and name it
as myapplication under a package com.example.myapplication as explained in
the Hello World Example chapter.
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.
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ch1=(CheckBox)findViewById(R.id.checkBox1);
ch2=(CheckBox)findViewById(R.id.checkBox2);
b1=(Button)findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StringBuffer result = new StringBuffer();
result.append("Thanks : ").append(ch1.isChecked());
result.append("\nThanks: ").append(ch2.isChecked());
Toast.makeText(MainActivity.this, result.toString(),
Toast.LENGTH_LONG).show();
}
});
}
}
Following will be the content of res/layout/activity_main.xml file −
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Example of checkbox"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Do you like Tutorials Point"
android:layout_above="@+id/button"
android:layout_centerHorizontal="true" />
<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Do you like android "
android:checked="false"
android:layout_above="@+id/checkBox1"
android:layout_alignLeft="@+id/checkBox1"
android:layout_alignStart="@+id/checkBox1" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/checkBox1"
android:layout_below="@+id/textView1"
android:layout_marginTop="39dp"
android:text="Tutorials point"
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_alignRight="@+id/textView1"
android:layout_alignEnd="@+id/textView1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ok"
android:id="@+id/button"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/checkBox1"
android:layout_alignStart="@+id/checkBox1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"
android:id="@+id/button2"
android:layout_alignParentBottom="true"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Following will be the content of res/values/strings.xml to define these new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">MyApplication</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.myapplication.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your MyApplication application. I assume you had created
your AVD while doing environment setup. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Android studio installs the app on your AVD and starts it and if everything is
fine with your setup and application, it will display following Emulator window −
User needs you check on either do you like android check box or do you like
tutorials point check box. and press ok button, if does all process correctly, it
gonna be shown toast message as Thanks. Or else do press on cancel button,
if user presses cancel button it going to close the application
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.
Example
This example demonstrates the horizontal use of the progress dialog which is
in fact a progress bar. It display a progress bar on pressing the button.
To experiment with this example, you need to run this on an actual device after
developing the application according to the steps below.
Steps Description
1 You will use Android studio to create an Android application under a
package com.example.sairamkrishna.myapplication.
4 Run the application and choose a running android device and install the
application on it and verify the results.
import android.app.ProgressDialog;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setIndeterminate(true);
progress.setProgress(0);
progress.show();
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"
android:text="Progress bar" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Download"
android:onClick="download"
android:id="@+id/button2"
android:layout_marginLeft="125dp"
android:layout_marginStart="125dp"
android:layout_centerVertical="true" />
</RelativeLayout>
This is the default AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. We assume, you have connected your actual
Android Mobile device with your computer. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Before starting your application, Android studio will display following window to
select an option where you want to run your Android application.
Select your mobile device as an option and then check your mobile device
which will display following screen −
Just press the button to start the Progress bar. After pressing, following screen
would appear −
It will continuously update itself.
4.2 .1 ListView:
Android ListView is a view which groups several items and display them
in vertical scrollable list. The list items are automatically inserted to the
list using an Adapter that pulls content from a source such as an array or
database.
List View
An adapter actually bridges between UI components and the data source
that fill data into UI Component. Adapter holds the data and send the
data to adapter view, the view can takes the data from adapter view and
shows the data on different views like as spinner, list view, grid view etc.
The ListView and GridView are subclasses of AdapterView and they
can be populated by binding them to an Adapter, which retrieves data
from an external source and creates a View that represents each data
entry.
Android provides several subclasses of Adapter that are useful for
retrieving different kinds of data and building views for an AdapterView
( i.e. ListView or GridView). The common adapters
are ArrayAdapter,Base
Adapter, CursorAdapter, SimpleCursorAdapter,SpinnerAdapter and
WrapperListAdapter. We will see separate examples for both the
adapters.
1 android:id
This is the ID which uniquely identifies the layout.
2 android:divider
This is drawable or color to draw between list items.
3 android:dividerHeight
This specifies height of the divider. This could be in px, dp, sp, in, or mm.
4 android:entries
Specifies the reference to an array resource that will populate the ListView.
5 android:footerDividersEnabled
When set to false, the ListView will not draw the divider before each footer
view. The default value is true.
6 android:headerDividersEnabled
When set to false, the ListView will not draw the divider after each header
view. The default value is true.
ArrayAdapter:
You can use this adapter when your data source is an array. By default,
ArrayAdapter creates a view for each array item by calling toString() on each
item and placing the contents in a TextView. Consider you have an array of
strings you want to display in a ListView, initialize a new ArrayAdapter using a
constructor to specify the layout for each string and the string array −
ArrayAdapter adapter = new
ArrayAdapter<String>(this,R.layout.ListView,StringArray);
Here are arguments for this constructor −
First argument this is the application context. Most of the case, keep
it this.
Second argument will be layout defined in XML file and
having TextView for each string in the array.
Final argument is an array of strings which will be populated in the text
view.
Once you have array adapter created, then simply call setAdapter() on
your ListView object as follows −
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
You will define your list view under res/layout directory in an XML file. For our
example we are going to using activity_main.xml file.
Example
Following is the example which will take you through simple steps to show how
to create your own Android application using ListView. Follow the following
steps to modify the Android application we created in Hello World
Example chapter –
Ste Description
p
1 You will use Android Studio IDE to create an Android application and name it
as ListDisplay under a package com.example.ListDisplay as explained in
the Hello World Example chapter.
6 Run the application to launch Android emulator and verify the result of the
changes done in the application.
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
<ListView
android:id="@+id/mobile_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Following will be the content of res/values/strings.xml to define two new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">ListDisplay</string>
<string name="action_settings">Settings</string>
</resources>
Following will be the content of res/layout/activity_listview.xml file −
<?xml version="1.0" encoding="utf-8"?>
<!-- Single List Item Design -->
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold" >
</TextView>
Let's try to run our modified Hello World! application we just modified. I
assume you had created your AVD while doing environment set-up. To run the
app from Android studio, open one of your project's activity files and click
Run icon from the tool bar. Android studio installs the app on your AVD and
starts it and if everything is fine with your set-up and application, it will display
following Emulator window −
SimpleCursorAdapter:
You can use this adapter when your data source is a database Cursor. When
using SimpleCursorAdapter, you must specify a layout to use for each row in
the Cursor and which columns in the Cursor should be inserted into which
views of the layout.
For example, if you want to create a list of people's names and phone
numbers, you can perform a query that returns a Cursor containing a row for
each person and columns for the names and numbers. You then create a
string array specifying which columns from the Cursor you want in the layout
for each result and an integer array specifying the corresponding views that
each column should be placed −
String[] fromColumns = {ContactsContract.Data.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
int[] toViews = {R.id.display_name, R.id.phone_number};
When you instantiate the SimpleCursorAdapter, pass the layout to use for each
result, the Cursor containing the results, and these two arrays −
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.person_name_and_number, cursor, fromColumns,
toViews, 0);
ListView listView = getListView();
listView.setAdapter(adapter);
The SimpleCursorAdapter then creates a view for each row in the Cursor using
the provided layout by inserting each from Columns item into the
corresponding toViews view.
4.2.2 GridView:
Android GridView shows items in two-dimensional scrolling grid (rows &
columns) and the grid items are not necessarily predetermined but they
automatically inserted to the layout using a ListAdapter
Grid view
An adapter actually bridges between UI components and the data source that
fill data into UI Component. Adapter can be used to supply the data to like
spinner, list view, grid view etc.
The ListView and GridView are subclasses of AdapterView and they can be
populated by binding them to an Adapter, which retrieves data from an
external source and creates a View that represents each data entry.
1 android:id
This is the ID which uniquely identifies the layout.
android:columnWidth
2
This specifies the fixed width for each column. This could be in px, dp, sp,
in, or mm.
android:gravity
3
Specifies the gravity within each cell. Possible values are top, bottom, left,
right, center, center_vertical, center_horizontal etc.
android:horizontalSpacing
4
Defines the default horizontal spacing between columns. This could be in
px, dp, sp, in, or mm.
android:numColumns
5 Defines how many columns to show. May be an integer value, such as
"100" or auto_fit which means display as many columns as possible to fill
the available space.
6 android:stretchMode
Defines how columns should stretch to fill the available empty space, if any.
This must be either of the values −
none − Stretching is disabled.
spacingWidth − The spacing between each column is stretched.
columnWidth − Each column is stretched equally.
spacingWidthUniform − The spacing between each column is
uniformly stretched..
android:verticalSpacing
7
Defines the default vertical spacing between rows. This could be in px, dp,
sp, in, or mm.
Example
This example will take you through simple steps to show how to create your
own Android application using GridView. Follow the following steps to modify
the Android application we created in Hello World Example chapter −
Step Description
1 You will use Android studio IDE to create an Android application and name it
as HelloWorld under a package com.example.helloworld as explained in the Hello
World Example chapter.
3 No need to change string.xml, Android studio takes care of defaults strings which
are placed at string.xml
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.GridView;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
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.
5 Run the application to launch Android emulator and verify the result of the
changes done in the application.
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;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
<ImageView
android:id="@+id/simpleImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/lion" />
paddingRight: set the padding from the right side of the image view.
paddingLeft: set the padding from the left side of the image view.
paddingTop: set the padding from the top side of the image view.
paddingBottom: set the padding from the bottom side of the image view.
padding: set the padding from the all side’s of the image view.
5. scaleType: scaleType is an attribute used to control how the image should be re-
sized or moved to match the size of this image view. The value for scale type attribute
can be fit_xy, center_crop, fitStart etc.
Example of ImageView:
Below is the example of imageview in which we display two animal images of
Lion and Monkey. And whenever user click on an image Animal name is
displayed as toast on screen. Below is the final output and code:
In this step we create a new project in android studio by filling all the
necessary details of the app like app name, package name, api versions etc.
Select File -> New -> New Project and Fill the forms and click "Finish"
button.
Step 2: Download two images lion and monkey from the web. Now save those
images in the drawable folder of your project.
Step 3: Now open res -> layout -> activity_main.xml (or) main.xml and add
following code:
In this step we add the code for displaying an image view on the screen in
a relative layout. Here make sure you have already saved two images name lion
and monkey in your drawable folder.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<ImageView
android:id="@+id/simpleImageViewLion"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:scaleType="fitXY"
android:src="@drawable/lion" />
<ImageView
android:id="@+id/simpleImageViewMonkey"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_below="@+id/simpleImageViewLion"
android:layout_marginTop="10dp"
android:scaleType="fitXY"
android:src="@drawable/monkey" />
</RelativeLayout>
Step 4: Now open app -> java -> package -> MainActivity.java and add the
following code:
In this step we add the code to initiate the image view’s and then perform click
event on them.
package example.abhiandriod.imageviewexample;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
Output:
Now start AVD in Emulator and run the App. You will see the images of Lion and
Monkey displayed on screen. Click on any Animal image and his name will
appear on Screen. We clicked on Lion.
4.2.4 ScrollView:
In android ScrollView can hold only one direct child. This means that, if you have
complex layout with more views(Buttons, TextViews or any other view) then you must
enclose them inside another standard layout like Table Layout, Relative
Layout or Linear Layout. You can specify layout_width and layout_height to adjust
width and height of screen. You can specify height and width in dp(density pixel) or
px(pixel). Then after enclosing them in a standard layout, enclose the whole layout
in ScrollView to make all the element or views scrollable.
ScrollView in Android Studio Design: It is present inside Containers >> ScrollView or
HorizontalScrollView
ScrollView Syntax:
<ScrollView
android:id="@+id/scrollView"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- add child view’s here -->
</ScrollView>
<ScrollView
android:id="@+id/scrollView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
< HorizontalScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="vertical"/><!--scrollbars in vertical direction-->
Select File -> New -> New Project -> Android Application Project (or) Android
Project. Fill the forms and click “Finish” button.
Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add below
code. Here we are creating a Relative Layout having 10 buttons which are nested
in Linear Layout and then in ScrollView.
Important Note: Remember ScrollView can hold only one direct child. So we
have to jointly put 10 buttons inside Linear Layout to make it one child. And then
we put it inside ScrollView.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="20dp"
android:orientation="vertical">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#f00"
android:text="Button 1"
android:textColor="#fff"
android:textSize="20sp" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#0f0"
android:text="Button 2"
android:textColor="#fff"
android:textSize="20sp" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#00f"
android:text="Button 3"
android:textColor="#fff"
android:textSize="20sp" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#ff0"
android:text="Button 4"
android:textColor="#fff"
android:textSize="20sp" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#f0f"
android:text="Button 5"
android:textColor="#fff"
android:textSize="20sp" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#f90"
android:text="Button 6"
android:textColor="#fff"
android:textSize="20sp" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#f00"
android:text="Button 7"
android:textColor="#ff9"
android:textSize="20sp" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#444"
android:text="Button 8"
android:textColor="#fff"
android:textSize="20sp" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#ff002211"
android:text="Button 9"
android:textColor="#fff"
android:textSize="20sp" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#0f0"
android:text="Button 10"
android:textColor="#fff"
android:textSize="20sp" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
Step 3: Now Open src -> package -> MainActivity.java and paste the below code
package com.example.gourav.scrollviewExample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Step 5: Lastly open res ->values -> strings.xml and paste the below code
<resources>
<string name="app_name">ScrollViewExample</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
</resources>
Output:
Now run the App in Emulator / AVD or in real device. You will see the 10 buttons
which can be scrollable in vertical direction.
4.2.5 Custom Toast Alert:
Project Structure :
File : res/drawable/toast_border.xml
Create style for custom toast layout.
File : res/layout/toast.xml
This file is used for custom toast layout.
<TextView
android:paddingLeft="10dp"
android:textColor="#ffffff"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="The image has been uploaded to server."
android:layout_gravity="center_vertical" />
</LinearLayout>
File : res/layout/activity_custom_toast.xml
Create main activity.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CustomToast"
android:background="#890000">
<TextView
android:paddingTop="20px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/Clickhere"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click here to see custom alert"
/>
</RelativeLayout>
File : src/CustomToast.java
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_toast);
@Override
public void onClick(View v) {
showCustomAlert();
}
});
}
}
}
In this section, we are going to demonstrate the use of Date Picker through
DatePickerDialog. DatePickerDialog is a simple dialog containing DatePicker.
In order to show DatePickerDialog , you have to pass the DatePickerDialog id
to showDialog(id_of_dialog) method. Its syntax is given below −
showDialog(999);
On calling this showDialog method, another method
called onCreateDialog gets automatically called. So we have to override that
method too. Its syntax is given below −
@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(this, myDateListener, year,
month, day);
}
return null;
}
In the last step, you have to register the DatePickerDialog listener and override
its onDateSet method. This onDateSet method contains the updated day,
month and year. Its syntax is given below −
private DatePickerDialog.OnDateSetListener myDateListener =
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker arg0, int arg1, int arg2,
int arg3) {
// arg1 = year
// arg2 = month
// arg3 = day
}
};
Apart form date attributes, DatePicker object is also passed into this function.
You can use the following methods of the DatePicker to perform further
operation.
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
8 getCalendarView()
This method returns calendar view
9 getFirstDayOfWeek()
This Method returns first day of the week
Example
Here is an example demonstrating the use of DatePickerDialog class. It
creates a basic Date Picker application that allows you to set the Date using
DatePicker Widget
To experiment with this example , you can run this on an actual device or in an
emulator.
Steps Description
1 You will use Android studio to create an Android application and name it as
DatePicker under a package com.example.datepicker.
5 Run the application and choose a running android device and install the
application on it and verify the results.
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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;
}
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:onClick="setDate"
android:text="@string/date_button_set" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="24dp"
android:text="@string/date_label_set"
android:textAppearance="?android:attr/textAppearanceMedium" /
>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_marginTop="66dp"
android:layout_toLeftOf="@+id/button1"
android:text="@string/date_view_set"
android:textAppearance="?android:attr/textAppearanceMedium" /
>
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/button1"
android:layout_below="@+id/textView2"
android:layout_marginTop="72dp"
android:text="@string/date_selected"
android:textAppearance="?android:attr/textAppearanceMedium" /
>
</RelativeLayout>
Following is the content of the res/values/string.xml.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">DatePicker</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="date_label_set">Press the button to set the
date</string>
<string name="date_button_set">Set Date</string>
<string name="date_view_set">The Date is: </string>
<string name="date_selected"></string>
</resources>
Let's try to run our DatePicker application we just modified. I assume you had
created your AVD while doing environment set-up. To run the app from
Eclipse, open one of your project's activity files and click Run icon from the
tool bar. Eclipse installs the app on your AVD and starts it and if everything is
fine with your set-up and application, it will display following Emulator window −
Now you can see that the date has already been set at the bottom label. Now
we will change the date through DatePickerDialog by pressing the Set Date
button. On pressing the button following screen would appear.
Now set the required date, and after setting the date, press the Done button.
This dialog will disappear and your newly setted date will start showing at the
screen. This is shown below.