Mad Unit-3
Mad Unit-3
Mad Unit-3
WHAT IS AN ACTIVITY?
An activity is one screen of an app. In that way the activity is very similar to a window in the
Windows operating system.The most specific block of the user interface is the activity. An
Android app contains activities, meaning one or more screens.
An activity class is per definition a class in Android. Every application which has UI must inherit
it to create a window.
DECLARE ACTIVITIES
Let’s start by declaring our activity. First, open your manifest file then add an element as a child
of the element.
Example:
<manifest ... >
<application ... >
<activity android:name=".ExampleActivity" />
...
</application ... >
...
</manifest >
seDebugValue(value)
Example:
<activity android:name=".ExampleActivity" android:icon="@drawable/app_icon">
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
In this example,
<action> element :- this activity sends data.
<category> element :- if we declare it as DEFAULT then it will allow the activity to get the
launch requests.
<data> element :- represents the type of data that an activity can send.
Example:- how to call the activity described.
// Create the text message with a string
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);
// Start the activity
startActivity(sendIntent);
If you don’t want to use any activity in other applications then you should not use the intent
filter, and you can start them by using explicit intents.
DECLARE PERMISSIONS
To control whether apps can start a specific activity we can use manifest’s <activity>. If parent
activity and child activity both have the same permissions it will not launch.
Example:- Let’s say you have a socialApp that shares a post on social media, then your social
media app should define permissions that an app
calling it must have.
<manifest>
<activity android:name="...."
android:permission=”com.google.socialapp.permission.
SHARE_POST”
/>
Your app must match the permission set in socialApp’s manifest so it can be allowed to call
socialApp.
<manifest>
<uses-permission android:name="com.google.socialapp.permission.
SHARE_POST" />
</manifest>
LIFECYCLE OF ACTIVITY
An activity goes through a number of states. Activity lifecycle in Android manages the different
states of activity, such as when the activity starts or stops, etc. All of these states are managed by
callback methods.
There are seven callback methods:-
onCreate():- This callback method must be created by you, this is fired when your activity is
created by the system. For example, when you open the app it will call onCreate(), onStart(), and
onResume() methods. These three methods are initiated when you open an app.
onStart():- There should always be an onStart() callback after onCreate() finishes. In the started
state users will be able to see the activity but they are not ready for user interaction.
onResume():- In this, activities will be in the foreground and ready for user interaction. You can
understand the use of this callback from this example: “when the user presses the phone’s answer
button it will give onPause() after you end up calling it will again give onResume()”.
onPause():- This callback occurs when there is a case of another activity starting in front of the
current activity. It is the opposite of onResume(). An example for this callback can be “when you
open the app, that is another app from the notification bar, or open settings then it will call
onPause() and onStop()”.
onStop():- It is the opposite of onStart(). In this case, activity will no longer be visible to the
users.
onRestart():- This occurs when the activity is stopped and before the activity starts again. It is a
less common callback.
onDestroy():- It is opposite of onCreate(). This starts when the system needs to free memory or
when finish() is called. It is used for cleanup which is a very common activity.
Implicit Intents:
Intent Classification:
Implicit Intent
Using implicit Intent, components can’t be specified. An action to be performed is declared by
implicit intent. Then android operating system will filter out components that will respond to the
action.The intent is a messaging object which passes between components like services, content
providers, activities, etc. Normally startActivity() method is used for invoking any activity. Some
of the general functions of intent are:
1. Start service
2. Launch Activity
3. Display web page
4. Display contact list
5. Message broadcasting
Methods and their Description
Methods Description
For Example,
In the above example, no component is specified, instead, an action is performed i.e. a webpage
is going to be opened. As you type the name of your desired webpage and click on the ‘CLICK’
button. Your webpage is opened.
Step by Step Implementation
Syntax:
android:id="@+id/id_name"
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn"
android:text="Click"
android:onClick="search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText" />
</androidx.constraintlayout.widget.ConstraintLayout>
Syntax:
ComponentType object = (ComponentType) findViewById(R.id.IdOfTheComponent);
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
EditText editText;
Button button;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.btn);
editText = (EditText) findViewById(R.id.editText);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String url=editText.getText().toString();
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
});
}
}
Explicit Intent
Using explicit intent any other component can be specified. In other words, the targeted
component is specified by explicit intent. So only the specified target component will be
invoked. For Example:
How to create an Android App to move to the next activity using Explicit Intent(with
Example)
Syntax:
android:id="@+id/id_name"
<TextView
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Welcome to GFG Home Screen"
android:textAlignment="center"
android:textSize="28sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn1"
android:text="Go to News Screen"
android:onClick="newsScreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText" />
</androidx.constraintlayout.widget.ConstraintLayout>
Syntax:
ComponentType object = (ComponentType) findViewById(R.id.IdOfTheComponent);
Intent i = new Intent(getApplicationContext(), <className>);
startActivity(i);
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
<TextView
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Welcome to GFG News Screen"
android:textAlignment="center"
android:textSize="28sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn2"
android:text="Go to Home Screen"
android:onClick="homeScreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText" />
</androidx.constraintlayout.widget.ConstraintLayout>
Syntax:
ComponentType object = (ComponentType) findViewById(R.id.IdOfTheComponent);
Intent i = new Intent(getApplicationContext(), <className>);
startActivity(i);
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
Android UI Controls are those components of Android that are used to design the UI in a
more interactive way. It helps us to develop an application that makes user interaction better with
the view components. Android provides us a huge range of UI controls of many types such as
buttons, text views, etc.
As we know UI is the only thing that a user interacts with within an Application. This is the
reason that we make our Application look aesthetic and, more and more connective. To do so, we
need to add the UI controls or we say Input controls in the respective application.
Moving forth we will see some important Android UI controls for our applications:
● TextView
● EditText
● Button
● ImageButton
● ToggleButton
● RadioButton
● RadioGroup
● CheckBox
● AutoCompleteTextView
● ProgressBar
● Spinner
● TimePicker
● DatePicker
● SeekBar
● AlertDialog
● Switch
● RatingBar
Android UI Controls
1. TextView
TextView is a UI Component that displays the text to the user on their Display Screen.
We can create it in two ways:
XML file:
For this, we declare it in the layout tag as follows:
<Linear Layout xmls:android= "http://schemas.android.com/apk/res/android"
<TextView
//attributes to describe it
/>
</LinearLayout>
Activity file:
In this, we declare it using the setText() method as follows:
setContentView(R.layout.activity_main);
LinearLayout linearlayout_name = (LinearLayout)findViewById(R.id.LinearLayout);
TextView textview_name = new TextView(this);
textview_name.setText(“Hello I am Text View”);
linearLayout.addView(textView);
There are various attributes to describe the TextView some of them are named below:
● Android: id – it is a unique id for the control.
● Android: width – It displays the exact width of the TextView.
● Android: height – It displays the exact height of the TextView.
● Android:textColor – It set the color of the text.
● Android: gravity – It is to align the TextView.
There are some more attributes the above are the major ones.
2. EditText
EditText is a user interface control that allows the users to enter some text.
We can create it in two ways:
XML file:
For this, we declare it in the layout tag as follows:
<Linear Layout xmls:android= ”http://schemas.android.com/apk/res/android”>
<EditText
//attributes
>
</LinearLayout>
Activity file:
In activity, we declare it using the getText() method as follows:
setContentView(R.layout.activity_main);
LinearLayout linearlayout_name = (LinearLayout) findViewById (R.id.LinearLayout) ;
EditText edittext_name = new EditText(this);
edittext_name.setHint(“Hello I am EditText”);
linearLayout.addView(edittext_name);
3. Button
This is a UI that is used to perform some action as soon as the user clicks on it.
We can create it in two ways:
XML file:
For this, we declare it in the layout tag as follows:
<Linear Layout xmls:android= ”http://schemas.android.com/apk/res/android”>
<Button
//attributes
/>
</LinearLayout>
Activity file:
In activity, we declare it programmatically as below:
setContentView(R.layout.activity_main);
LinearLayout linearlayout_name = (LinearLayout)findViewById(R.id.LinearLayout);
Button btn_name = new Button(this);
btn_name.setText(“Hello I am Button”);
linearLayout.addView(btn_name);
4. ImageButton
It is the same as a Button but it’s used to display an image on the button to perform an Action. In
this, we need to give the source of the image so that the system can load it.
We can create it in two ways:
XML file:
For this, we declare it in the layout tag as follows:
<Linear Layout xmls:android= ”http://schemas.android.com/apk/res/android”>
<ImageButton
//other attributes...
android:src= “@drawable/add_icon”/>
</LinearLayout>
Activity file:
In the activity file, we declare it programmatically as below:
setContentView(R.layout.activity_main);
LinearLayout linearlayout_name = (LinearLayout)findViewById(R.id.LinearLayout);
ImageButton btn_name = new Button(this);
btn_name.setImageResource(R.drawable.add_icon);
linearLayout.addView(btn_name);
5. ToggleButton
The toggle button displays the ON/OFF states of a button with a light indicator.
We can create it in two ways:
XML file:
For this, we declare it in the layout tag as follows:
<Linear Layout xmls:android= ”http://schemas.android.com/apk/res/android”>
<ToggleButton
//attributes
android:checked="true"
android:textOff="OFF"
android:textOn="ON"/>
</LinearLayout>
Activity file:
In the activity file we declare it programmatically as below:
setContentView(R.layout.activity_main);
LinearLayout linearlayout_name = (LinearLayout)findViewById(R.id.LinearLayout);
ToggleButton tb_name = new ToggleButton(this);
tb_name.setTextOff("OFF");
tb_name.setTextOn("ON");
tb_name.setChecked(true);
linearLayout.addView(btn_name);
6. RadioButton
Radio button in Android is the one that has only two possible states, that are either checked or
unchecked. Initially, it is in the unchecked state, once it’s checked it can’t be unchecked.
We can create it in two ways:
XML file:
For this, we declare it in the layout tag as follows:
<Linear Layout xmls:android= ”http://schemas.android.com/apk/res/android”>
<RadioButton
android:text="Radio button"
android:checked="true"/>
</LinearLayout>
Activity file:
In the activity file, we declare it programmatically as below:
setContentView(R.layout.activity_main);
LinearLayout linearlayout_name = (LinearLayout)findViewById(R.id.LinearLayout);
RadioButton btn_name = new RadioButton(this);
btn_name.setText("Hello");
btn_name.setChecked(true);
linearLayout.addView(btn_name);
7. RadioGroup
It’s a group of Radio buttons that are alike. In this, only one of all the buttons can be chosen.
We can create it in two ways:
XML file:
For this, we declare it in the layout tag as follows:
<Linear Layout xmls:android= ”http://schemas.android.com/apk/res/android”>
<RadioGroup android:orientation="vertical">
<RadioButton android:text="Radio Button 1"/>
<RadioButton android:text="Radio Button 2"/>
<RadioButton android:text="Radio Button 3"/>
</RadioGroup>
</LinearLayout>
Activity file:
In the activity file, we declare it programmatically as below:
RadioButton rdb1,rdb2,rdb3;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rdb1 = (RadioButton)findViewById(R.id.rdb_1);
rdb2 = (RadioButton)findViewById(R.id.rdb_2);
rdb3 = (RadioButton)findViewById(R.id.rdb_3);
Button btn = (Button)findViewById(R.id.getBtn);
}
Above is the example to declare it, to make it functional, we would override and define the
methods that are required.
8. CheckBox
A CheckBox is the UI control that has two states that are either checked or unchecked. If we
have a group of CheckBox, we can select as many as we want, unlike RadioGroup.
We can create it in two ways:
XML file:
For this, we declare it in the layout tag as follows:
<Linear Layout xmls:android= ”http://schemas.android.com/apk/res/android”>
<CheckBox
android:checked="true"
android:text="CheckBox"
// other attributes
/>
</LinearLayout>
Activity file:
In activity, we declare it programmatically as below:
setContentView(R.layout.activity_main);
LinearLayout linearlayout_name = (LinearLayout)findViewById(R.id.LinearLayout);
CheckBox cb_name = new CheckBox(this);
cb_name.setText("DataFlair");
cb_name.setChecked(true);
layout.addView(cb_name);
9. ProgressBar
In Android, we have a progress bar that shows the progress of some action that is happening like
pasting a file to some location. A progress bar can be in two modes:
● Determinate Mode:
In this, the progress is shown with the percent of action completed. Also, the time to be taken is
already determined.
● Indeterminate Mode:
In this, there is no idea of when the task would be completed, therefore, it functions
continuously.
We can create it in two ways:
XML file:
For this, we declare it in the layout tag as follows:
<Linear Layout xmls:android=”http://schemas.android.com/apk/res/android”>
<ProgressBar
// attributes, here we define the speed, layout, id, etc.
/>
</LinearLayout>
Activity file:
In activity, we declare it programmatically as below:
setContentView(R.layout.activity_main);
pgsBar = (ProgressBar)findViewById(R.id.pBar);
txtView = (TextView)findViewById(R.id.tView);
Button btn = (Button)findViewById(R.id.btnShow);
Here we need to set the sleep time and override the onClick() and onCreate() methods
The above were some of the very important UI controls, now we will also read about some more
UI controls :
1. Spinner
The Spinner in Android is a User Interface that is used to select a particular option from a list of
given options. Spinner in Android is the same as dropdown in HTML. It provides us with a faster
way to select an option of our choice. When we click on the down arrow, it shows a list of values
from which we can select one. By default, the first value would be shown as the currently
selected Value.
2. TimePicker
Time picker is a UI component that works as an intermediate to select a time of the day. The time
chosen by it is shown either in 24 hrs format or in 12hrs format using AM and PM.
It gives a virtual Clock/watch to select it. This virtual clock makes it easy to choose the time.
3. DatePicker
Like we have time picker, we have a date picker as UI control too. In this, the System shows a
virtual calendar to the users to choose the day.
This enables the user to choose a particular date using either a calendar or a dropdown. These
both are made to make it easier for the user to pick up a date and a time.
4. SeekBar
In Android, Seekbar is an extended Progress bar. A seekbar comes with a pointer that is
draggable throughout the bar either in left or right. This pointer helps to set the progress as well.
This helps the user to choose a particular range of values.
5. RatingBar
A rating bar in Android is an extended version of a seekbar. It is used to give the rating by
touching it. In the rating bar, a user can rate at a scale of 5 with a difference of 0.5.
Its rating is in Stars. The user needs to tap/click the stars.
6. AlertDialog
Alert Dialog Box is a UI that gives the users an Alert or Warning of something. It appears on the
screen in a small window. Once it comes, the user needs to decide or choose an option that it
shows.
For example, when you enter the wrong password for email id.
7. Switch
In Android, a switch is a two-state UI element that holds either ON or OFF state. ON generally
means Yes and OFF means No. By default, a switch is in the OFF state. A user can change its
state many times.
8. AutoCompleteTextView
AutoCompleteTextView is an extension of EditText. In this UI element, the user is provided with
a few suggestions of some values/texts. The value can be chosen by the user while filling
AutoCompleteTextView.
Android adapters provide a common interface to the data model behind the selection
widgets. They are responsible for providing the data for a selection widget, as well as for
converting individual elements of data into specific views to be displayed inside the widgets.
The easiest adapter to use is ArrayAdapter. All we need to do is wrap around a Java array or
java.util.List instance. Then, we have a fully functional adapter:
String[] arr = {"My", "first", "Android", "list"};
new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1, arr);
The ArrayAdapter constructor takes following three parameters:
1. The Context to use, typically, this will be our activity instance.
2. The resource ID of a view to use, for example, built in resource ID.
3. The actual array or list.
The ArrayAdapter will invoke toString() on the objects in the list and wrap each of those strings
in the view designated by the supplied resource.
android.R.layout.simple_list_item_1 simply turns those strings into TextView objects. And those
TextView widgets, in turn, will be shown in the list, spinner, etc.
GridView:
A GridView displays items in a two-dimensional, scrolling grid. We have moderate control over
the number and size of the columns and the number of rows is dynamically determined based on
the number of items. The items are acquired from a ListAdapter.
Following properties determine the number of columns and their sizes:
1. android:numColumns
Specifies how many columns there are, of if we supply a value of auto_fit, Android will
compute the number of columns based on the available space and the following
properties.
2. android:verticalSpacing and android:horizontalSpacing
Indicate how much whitespace there should be between items in the grid.
3. android:columnWidth
Indicates how many pixel wide each column should be.
4. android:stretchMode
Indicates, for grids with auto_fit for android:numColumns, what should happen for any
available space not taken up by columns or spacing. This can be columnWidth, to have
the columns taken up available space, or spacingWidth, to have the whitespace between
columns absorb extra space.
Layout file:
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android=
"http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:columnWidth="90dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
import com.bogotobogo.GView.ImageAdapter;
import com.bogotobogo.GView.R;
import android.app.Activity;
import android.os.Bundle;
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;
public ImageAdapter(Context c) {
mContext = c;
}
First we take care of some required methods inherited from BaseAdapter. The constructor and
getCount() are self-explanatory. Normally, getItem() should return the actual object at the
specified position in our Adapter, but for our case, we're not going to bother. Likewise,
getItemId() should return the row id of the item, but right now we don't care.
However, getView() is the method we care about. This one creates a new View for each image
that we put in our ImageAdapter. So we're going to create an ImageView each time. When this is
called, we're going to receive a View, which is likely a recycled View object (at least after the
first call), so we check for this, if it's null, we initialize the ImageView and setup all the
properties we want.
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
The LayoutParams() initialization sets the height and width of the View,this ensures that no
matter the drawable size, each image is resized and cropped to fit in the ImageView (if
necessary).
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
With setScaleType(), we say that images should be cropped toward the center (if necessary).
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
And finally, we set the padding within the ImageView. (Note that, if the images have various
aspect-ratios, as they do in our case, then less padding will cause for more cropping of the image,
if it does not match the dimensions given to the ImageView.)
imageView.setPadding(8, 8, 8, 8);
At the end of getView() we set the image resource and return the ImageView.
imageView.setImageResource(mThumbIds[position]);
ListView:
Displaying lists is a very common. The user gets a list of items that can be scrolled. Then, the
user select one item. Android provides the view ListView for this.
ListView is a ViewGroup that creates a list of scrollable items. The list items are
automatically inserted to the list using a ListAdapter, and we use attached listener via
setOnItemSelectedListener() to find out when the selection has changed.
But, if our activity is dominated by a single list, we might consider creating our activity as a
subclass of ListActivity, rather than the regular Activity class. If main view is just the list, we do
not even need to supply a layout; ListActivity will construct a full-screen list for us. If we want
to customize the layout, ListActivity knows which widget is the main list for the activity as long
as we identify our ListView as @android:id/list.
Now, let's work on real list example. We'll create a scrollable list of country names that are
read from a string array. We make the class extend ListActivity instead of Activity.
ListActivity is an activity that displays a list of items by binding to a data source such as an
array or Cursor, and exposes event handlers when the user selects an item. ListActivity hosts a
ListView object that can be bound to different data sources, typically either an array or a Cursor
holding query results.
Notice that we don't need to load a layout because we're using the whole screen for our list.
ListActivity has a default layout that consists of a single, full-screen list in the center of the
screen.
We call setListAdapter() which automatically adds a ListView to the ListActivity, and provide
it with an ArrayAdapter that binds a simple_list_item_1 layout item to each entry in the
WORLDCUP2010 array.
The ListAdapter manages a ListView backed by an array of arbitrary objects. By default this
class expects that the provided resource id references a single TextView.
Android provides some standard row layout resources. These are in the R.layout class, and
have names such as simple_list_item_1, simple_list_item_2, and two_line_list_item.
The setTextFilterEnabled(boolean) method turns on text filtering for the ListView, so that when
the user begins typing, the list will be filtered.
package com.bogotobogo.SimpleListView;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
A Spinner is a widget that allows the user to select an item from a group. It displays one child
at a time and lets the user pick among them. The items in the Spinner come from the Adapter
associated with this view. It is similar to a dropdown list and will allow scrolling when the list
exceeds the available vertical space on the screen.
Here is the layout file, main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="10dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView android:id="@+id/select"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:text="@string/select" />
<Spinner
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="true"
android:prompt="@string/planet_prompt"/>
</LinearLayout>
Because the Spinner's android:prompt is a string resource and Android does not allow it to be a
string, it must be a reference to a resource.
So we need to add an element inside the element. Open the strings.xml file in res/values/ put the
following into the file:
<string name="planet_prompt">Choose a planet</string>
Then, create a new XML file in res/values/ called arrays.xml. Insert the following list of planet
items that the user can select from in the Spinner widget.
<resources>
<string-array name="planets">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>
</resources>
with strings.xml:
<?xml version="1>0" encoding="utf-8"?>
<resources>
</resources>
package com.bogotobogo.SimpleSpinner;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
We then create an ArrayAdapter that binds each element of our string array to a layout view, we
pass createFromResource our Context, the array of selectable items and the type of layout we'd
like each one bound to.
ArrayAdapter adapter = ArrayAdapter.createFromResource(
this, R.array.planets, android.R.layout.simple_spinner_item);
We then call setDropDownViewResource() to define the type of layout in which to present the
entire collection.
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Finally, we set this Adapter to associate with our Spinner, so the string items have a place to go.
s.setAdapter(adapter);
An adapter basically connects the User Interfaces and the Data Source. According to Android
officials, “An Adapter object acts as a bridge between an AdapterView and the data for that view.
Android Adapters basically provides access to the data items.”
So we know, an adapter implements the Adapter Interface and acts as a link between a data
set and an adapter view. An AdapterView is an object of a class extending the abstract
AdapterView class. Now when we talk about the data, it can be anything that is present in
Structured Manner. It also retrieves data from data set & generates view objects based on that
data. It shows the data in different views like GridView, ListView, Spinners, etc.
1. ListView
The speciality of ListView is that it shows the items in a Horizontal form, here each item lies
below the other. These items are displayed in Vertically- Scrollable collection. Example is:
2. GridView
In a Grid View, each item is displayed in a tabular form or a 2-Dimensional view, that is in rows
and columns. This is also a vertically-scrollable view. To understand this view, consider:
3.Spinner:
Spinner view is a different view when we talk about all three. In Spinner, we get to choose a
value from a list of Values. This is like a dropdown menu that has a set of values in it.
Types of Android Adapters:
Android provides us with following different types of Adapters that are used to fill the data in UI
components:
● BaseAdapter – BaseAdapter is the parent adapter for the rest of the Adapters.
● CursorAdapter – This adapter makes it easy and more controlled to access the binding of
data values.
● ArrayAdapter – ArrayAdapter presents the items in a single list backed by an array.
● Custom ArrayAdapter – It displays the custom list of an Array.
● SimpleAdapter – SimpleAdapter is an easy adapter to map static data to the views
through the XML file.
● Custom SimpleAdapter – It displays a customized list and enables us to access the child
data of the list or grid view.
Now, we will see all these Android Adapters one by one:
1. BaseAdapter in Android
Base Adapter is a general implementation of an Adapter that is extended in other Android
Adapters for their use.
Other android adapters extend it to create a custom Adapter for displaying a common custom list
item. To extend a BaseAdapter in a customized adapter we extend it as follows:
public class My_Adapter extends BaseAdapter{
//overridden methods
public int getCount(){
//code
}
public Object getItem(int i) {
//code
}
// other methods
}
2. ArrayAdapter in Android
Whenever we need to arrange the data in ArrayList, we use the ArrayAdapter. The array adapter
uses Object.toString() for each data object to create a view, and then place the result in a
TextView. This type of android adapter is used for ListView, GridView or Spinner.
To include it we can use ArrayAdapter as follows:
ArrayAdapter ( Context context, int resource, int textViewResourceId, Item[] objects)
ArrayAdapter is a class and can have various types of Constructors, those constructors are
mentioned below:
● ArrayAdapter( Context context, int resource)
● ArrayAdapter( Context context, int resource, int textViewResourceId)
● ArrayAdapter( Context context, int resource, T[] objects)
● ArrayAdapter( Context context, int resource, textViewResourceId, T[] objects)
● ArrayAdapter( Context context, int resource, List<T> objects)
● ArrayAdapter( Context context, int resource, int textViewResourceId, List<T> objects)
4. CursorAdapter in Android
We use CursorAdapter when we need to display some data using the SQLite database query. This
Android Adapter enables us to use the resources easily in ListView.
To use it we can do the following:
public class MyCursorAdapter extends CursorAdapter {
// Constructor and required methods
}
5. SimpleAdapter in Android
A simple Adapter is used for static data that does not change dynamically. It provides an easy
way to add static data in a view that are defined in the XML file. We can add it using the
following:
SimpleAdapter (Context context, List<? Extends Map<String, ?>> data, int resource, String[]
from, int[] to)
There are certain methods of Adapter class that are mentioned below:
● getCount() – This method represents the number of items present in the data set.
● hasStableIds() – This method indicates whether the Item Ids are stable under changes on
the underlying data.
● getItem(int position) – This method gets the data item associated with a particular
position in the data set.
● getItemId(int position) – This method gets the Id of the item associated with a particular
position in the list.
● getViewTypeCount() – This method returns the number of types of Views created using
getView().
● getItemViewType(int position) – This method gets the type of View that would be created
using the getView() method.
● getView(int position, View convertView, ViewGroup parent) – This method displays the
data at a position in the data set.
● registerDataSetObserver(DataSetObserver observer) – This method registers the observer
that is called when the changes in the data occur.
● unregisterDataSetObserver(DataSetObserver observer) – This method unregisters the
observer that was registered using the registerDataSetObserver(DataSetObserver
observer) method.
Custom Adapters:
Customadapter extends Baseadapter and it is very flexible i.e. it allows you to do pretty
much whatever you want whereas ArrayAdapter is a more complete implementation that works
well for data in arrays or ArrayLists. Similarly, there is a related CursorAdapter that you should
use if your data is in a Cursor.BaseAdapter as its name implies, is the base class for so many
concrete adapter implementations on Android. It is abstract and therefore, cannot be directly
instantiated.
This example demonstrates how do I add custom adapter for my listView in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required
details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<MyData> arrayList = new ArrayList<>();
MyAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
arrayList.add(new MyData(1, " Mashu","987576443"));
arrayList.add(new MyData(2, " Azhar","8787576768"));
arrayList.add(new MyData(3, " Niyaz","65757657657"));
adapter = new MyAdapter(this, arrayList);
listView.setAdapter(adapter);
}
}
Step 4 − Create a java class(MyData.java) and add the following code
public class MyData {
private int serialNum;
private String name;
private String mobileNumber;
public MyData(int num, String name, String mobileNumber) {
this.serialNum = num;
this.name = name;
this.mobileNumber = mobileNumber;
}
public int getNum() {
return serialNum;
}
public void setNum(int num) {
this.serialNum = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
}