0% found this document useful (0 votes)
4 views11 pages

66d29a105c5ec1d3fd55a502 Lab5 Spinner ListView Custom-ListView

The document provides instructions for creating a Spinner and a ListView in Android. It details the layout and Java code necessary to implement a Spinner that allows users to select one item from a list, as well as a ListView that displays a list of student codes. Additionally, it covers creating a custom ListView with a custom adapter to display more complex data structures, including multiple TextViews and an avatar.

Uploaded by

thangvnde180947
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views11 pages

66d29a105c5ec1d3fd55a502 Lab5 Spinner ListView Custom-ListView

The document provides instructions for creating a Spinner and a ListView in Android. It details the layout and Java code necessary to implement a Spinner that allows users to select one item from a list, as well as a ListView that displays a list of student codes. Additionally, it covers creating a custom ListView with a custom adapter to display more complex data structures, including multiple TextViews and an avatar.

Uploaded by

thangvnde180947
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Instructions for making spinner and listview

1/ SPINNER

Spinner is a view used to display a list of lists like a listview, but only select
one option in that list .
In cases where it is necessary to list out a bunch of lists for people to choose
one, such as choosing a language, place of birth, city ... most things use Spinner.
However, if you customize the Spinner, you can select multiple options, not
just one.
The problem is, when the user selects an item, Toast announces the name of
that item.
The layout is as follows:
< FrameLayout 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= "com.example.webmasterdotnetvn.vidusukien.SpinnerActivity" >

< Spinner
android :id= "@+id/spnCategory"
android :layout_width= "match_parent"
android :layout_height= "50dp" />

</ FrameLayout >


Code to handle in Java:
package com.example.webmasterdotnetvn.vidusukien;

Page 1
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/** * Created
by [email protected] on 11/10/2017 .
*/
public class SpinnerActivity extends AppCompatActivity {
private Spinner spnCategory ;
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout. spinner );

spnCategory = (Spinner) findViewById(R.id. spnCategory );

List<String> list = new ArrayList<>();


list.add( "Java" );
list.add( "Android" );
list.add( "PHP" );
list.add( "C#" );
list.add( "ASP.NET" );

ArrayAdapter<String> adapter = new ArrayAdapter( this , android.R.layout.


simple_spinner_item ,list);
adapter.setDropDownViewResource(android.R.layout. simple_list_item_single_choice );
spnCategory .setAdapter(adapter);
spnCategory .setOnItemSelectedListener( new
AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int
i, long l) {
Toast. makeText (SpinnerActivity. this , spnCategory .getSelectedItem().toString(),
Toast. LENGTH_SHORT ).show();
}

@Override
public void onNothingSelected(AdapterView<?> adapterView) {

} }); }}

ArrayList to store the items that will show up when the Spinner is clicked.
Here is a String array.
List <String> list = new ArrayList<>();
list.add( "Java" );
list.add( "Android" );
list.add( "PHP" );
list.add( "C#" );
list.add( "ASP.NET" );

We get the "list" object, which contains elements such as: Java, Android, PHP,
C#, ASP.NET.
Next will see this line:
ArrayAdapter<String> adapter = new ArrayAdapter( this , android.R.layout.
simple_spinner_item ,list);

Page 2
After that, anything that uses the list must use ArrayAdapter .
Here the ArrayAdapter is the intermediary bridge between the View and the
data, as on the data here is the list, the data cannot be put directly to the View but must
go through this object.
Here there are 3 parameters passed in:
- this: is to get the current Activity
- android.R.layout.simple_spinner_item : this is a template that displays a list
that android has predefined, above can see items arranged vertically and row by
row, with black text color. If you want the text color to be blue, for example,
you can customize it and replace android.R.layout.simple_spinner_item with a
separate layout file.
- list : is some list of Objects, String is also Object.
Next:
adapter.setDropDownViewResource(android.R.layout. simple_list_item_single_choice );

The above line means that the format for this Spinner is single choice, when
you add the above method, you will see a pink circle button when selecting an item,
looking back on the image above will see, without this line, you will not see the icon.
Where is that statue?
Next:
spnCategory .setAdapter(adapter);

This line means set the Adapter on to the spinner, just now made the interface,
put the data into the Adapter, now just put it on the Spinner, that's the meaning of the
above command line.
Catching the event when selecting an item in the Spinner would look like this:
spnCategory .setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long
l) {
Toast. makeText (SpinnerActivity. this , spnCategory .getSelectedItem().toString(),
Toast. LENGTH_SHORT ).show();
}

@Override
public void onNothingSelected(AdapterView<?> adapterView) {

}});

Here when setOnItemSelectedListener for Spinner will catch Override 2


methods are:
- onItemSelected: call this function when there is an event to select an item.

Page 3
- onNothingSelected: call this function when clicking on Spinner without
selecting any item
2/ LISTVIEW
This is a view Group, used to display a list of certain objects in Android
vertically from the top and use the Adapter to bridge the data up.
The simplest listView example is as follows:

Above is a list of student codes generated from an array dropped onto the
listview. Here is the layout file:
<? xml version= "1.0" encoding= "utf-8" ?>
< LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: tools = "http://schemas.android.com/tools"
android :layout_width= "match_parent"
android :layout_height= "match_parent" >

< ListView
android :id= "@+id/lvMaSinhVien"
android : layout_width = "match_parent"
android :layout_height= "match_parent" />
</ LinearLayout >

And here is the Java code that handles the data put on the ListView:
package com.example.webmasterdotnetvn.vidusukien;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget. ArrayAdapter ;
import android.widget.ListView;

Page 4
/**
* Created by [email protected] on 11/10/2017. */
public class LisviewActivity extends AppCompatActivity {
private ListView lv ;
private String[] number = { "161250533502" , "161250533405" , "151250533308" ,
"161250533207" , "151250533113" , "131250532378" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout. listview_main );

lv = (ListView) findViewById(R.id. lvMaSinhVien );


ArrayAdapter arrayAdapter = new ArrayAdapter ( this ,android.R.layout.
simple_list_item_1 , number );

lv .setAdapter(arrayAdapter);

}}

The above creates a String array that is a list of student codes as follows:
private String[] number = { "161250533502" , "161250533405" , "151250533308" ,
"161250533207" , "151250533113" , "131250532378" };

Why create String array because currently ArrayAdaper is using is passing an


object, here is a String array, see code:
ArrayAdapter arrayAdapter = new ArrayAdapter (Context context, int resource,
List<T> objects);

- context: is the current activity/fragment .


- resource: this is the listview interface will display, inside the example is
showing the default interface of the Android library provided, it only has 1 line
to display the student code. In case you want to have Avatar inside student
code and delete icon, favorite... then you must create and customize yourself.
- List<T> objects: this is a Generic type in java, here pass a String array of
student codes to display on each listView item.
ArrayAdapter arrayAdapter = new ArrayAdapter( this ,android.R.layout.
simple_list_item_1 , number );

In the above step, it means that you have used the Adapter to store data to put it
on the ListView to understand it, now just call the setAdapter() method for the
listview and you're done:
lv .setAdapter(arrayAdapter);

Page 5
3/ Custom ListView

With the above Layout, just do the following steps:


1. yout file for the rows (items) in the listView.
2. Create a middle class for Contact
3. Create a CustomAdapter class to customize the listview for the layout created
above .
4. Call CustomAdapter to get the data.
Step 1:
The layout file above will include 2 TextViews and below is that layout file:
row_listview.xml
<? xml version= "1.0" encoding= "utf-8" ?>
< LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
android :layout_width= "match_parent"
android :layout_height= "match_parent"
android :orientation= "vertical" >
< LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"

Page 6
xmlns: tools = "http://schemas.android.com/tools"
android :layout_width= "match_parent"
android :layout_height= "match_parent"
android :orientation= "vertical" >

< LinearLayout
android :layout_width= "match_parent"
android :layout_height= "wrap_content"
android :layout_margin= "16dp"
android :orientation= "horizontal" >

< TextView
android :id= "@+id/tvAvatar"
android :layout_width= "70dp"
android :layout_height= "70dp"
android :background= "#18ade4"
android :gravity= "center"
android :text= "1"
android :textColor= "#ffffff"
android :textSize= "28sp"
android :textStyle= "bold" />

< LinearLayout
android :layout_width= "wrap_content"
android :layout_height= "wrap_content"
android :layout_gravity= "center"
android :layout_marginLeft= "50dp"
android :orientation= "vertical" >

< TextView
android :id= "@+id/tvName"
android :layout_width= "wrap_content"
android :layout_height= "wrap_content"
android :layout_gravity= "center"
android :text= "BOI WRONG ANH"
android :textSize= "16sp"
android :textStyle= "bold" />

< TextView
android :id= "@+id/tvMaSinhVien"
android :layout_width= "wrap_content"
android :layout_height= "wrap_content"
android :layout_gravity= "center"
android :text= "161250533502"
android :textSize= "16sp"
android :textStyle= "bold" />
</ LinearLayout >
</ LinearLayout >
</ LinearLayout >
</ LinearLayout >

Step 2:
This is the Contact class designed to create an object that stores the items of the
listview, here are the rows. How to create Constructer and getter(), setter() is learned
in basic Java.
This contact will have properties like:
- Name: Displays the username.
- PhoneNumber: display the phone number.
- Color: the color of the avatar.
Page 7
Contact.java
package com.example.webmasterdotnetvn.vidusukien;

/** * Created
by [email protected] on 11/10/2017 .
*/
public class Contact {
private String name ;
private String idStudent ;
private int color ;

public Contact(String name, String idStudent, int color) {


this . name = name;
this . idStudent = idStudent;
this . color = color;
}

public String getName() {


return name ;
}

public void setName(String name) {


this . name = name;
}

public String getIdStudent() {


return idStudent ;
}

public void setIdStudent(String idStudent) {


this . idStudent = idStudent;
}

public int getColor() {


return color ;
}

public void setColor( int color) {


this . color = color;
}}

Step 3:
Like the previous listview lesson, we don't custom ArrdayAdapter but use the
available library Android already has, so the listview only displays data in the form of
1 text on 1 row, and now on a row we If you have up to 3 image views, you can't use
it, but we have to customize it so that the data can be displayed.
CustomAdapter.java
package com.example.webmasterdotnetvn.vidusukien;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**

Page 8
* Created by [email protected] on 3/11/2018.
*/
public class CustomAdapter extends ArrayAdapter<Contact> {
private Context context ;
private int resource ;
private List<Contact> arrContact ;

public CustomAdapter(Context context, int resource, ArrayList<Contact>


arrContact) {
super (context, resource, arrContact);
this . context = context;
this . resource = resource;
this . arrContact = arrContact;
}

@Override
public View getView( int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder; if (convertView == null ) {
convertView = LayoutInflater. from ( context ).inflate(R.layout. row_listview ,
parent, false );
viewHolder = new ViewHolder();
viewHolder. tvName = (TextView) convertView.findViewById(R.id. tvName );
viewHolder. tvNumberPhone = (TextView) convertView.findViewById(R.id. tvMaSinhVien
);
viewHolder. tvAvatar = (TextView) convertView.findViewById(R.id. tvAvatar );

convertView.setTag(viewHolder); } else {
viewHolder = (ViewHolder) convertView.getTag(); } Contact contact = arrContact
.get(position);
viewHolder. tvAvatar .setBackgroundColor(contact.getColor());
viewHolder. tvAvatar .setText(String. valueOf (position+ 1 ));
viewHolder. tvName .setText(contact.getName());
viewHolder. tvNumberPhone .setText(contact.getIdStudent());
return convertView;
}

public class ViewHolder {


TextView tvName , tvNumberPhone , tvAvatar ;

}}

Here, the CustomAdaper class inherits ArrayAdapter<> which has a Generic


type of Contact, which means it only accepts a data type of Contact. When inheriting,
it is mandatory to override the @Override constructor as:
public CustomAdapter(Context context, int resource, ArrayList<Contact> arrContact)
{
super (context, resource, arrContact);
this . context = context;
this . resource = resource;
this . arrContact = arrContact;
}

Here will pass the params as above, see this command line again:
ArrayAdapter arrayAdapter = new ArrayAdapter( this ,android.R.layout.
simple_list_item_1 , number );

Customizing the Adapter, when used, will also call that Adapter and pass the
parameters in, here change:
android.R.layout.simple_list_item to the layout designed above row_listview.xml,
and the list number above will be replaced by another Contact list.

Page 9
Next is the getView() method, this is the method to initialize the view to add it
to the Listview, here it will create rows on the listview and set the data as Contacts on
those rows.
@Override
public View getView( int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder; if (convertView == null ) {
convertView = LayoutInflater. from ( context ).inflate(R.layout. row_listview ,
parent, false );
viewHolder = new ViewHolder();
viewHolder. tvName = (TextView) convertView.findViewById(R.id. tvName );
viewHolder. tvNumberPhone = (TextView) convertView.findViewById(R.id. tvMaSinhVien
);
viewHolder. tvAvatar = (TextView) convertView.findViewById(R.id. tvAvatar );

convertView.setTag(viewHolder); } else {
viewHolder = (ViewHolder) convertView.getTag(); } Contact contact = arrContact
.get(position);
viewHolder. tvAvatar .setBackgroundColor(contact.getColor());
viewHolder. tvAvatar .setText(String. valueOf (position+ 1 ));
viewHolder. tvName .setText(contact.getName());
viewHolder. tvNumberPhone .setText(contact.getIdStudent());
return convertView;
}

Here use ViewHolder to setTag() and getTag() when initializing the view.
Actually, if the listview has only a few rows, when swiping up and down is very
smooth, but if there are 1000 rows, it will be different, it will be very laggy
(Recyclerview uses smoother than listview).
Therefore, this ViewHolder was born to overcome, when sliding the listview
up and down, if these rows have already been initialized, it will be saved in the Tag
and will not be reinitialized by gettingTag out.
Because when calling the CustomAdaper class in MainActivity will pass it a
Contact list, the above code will have the effect of taking out each Contact one by one,
corresponding to each view, when getting the contact it will get the data of a Contact
such as: name , idStudent, color… and this data will be set on the row of the listview.
And finally return the convertView which are the rows that we have created
and set the data up.
Step 4:
As I said in the previous post, the Adapter is responsible for the intermediary to
store the data displayed on the listview, here it is similar to calling the CustomAdapter
and then passing the Contact array to it to process and put in the row.
ListviewActivity.java
package com.example.webmasterdotnetvn.vidusukien;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
Page 10
import java.util.ArrayList;

/**
* Created by [email protected] on 11/10/2017. */
public class LisviewActivity extends AppCompatActivity {
private ListView lvContact ;

@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout. listview_main );
lvContact = (ListView) findViewById(R.id. lvContact );
ArrayList<Contact> arrContact = new ArrayList<>();

Contact contact1 = new Contact( " Visit Hung Anh" , "161250533502" , Color . RED )
; Contact contact2 = new Contact( "Nguyen Quoc Cuong" , "161250533405" , Color.
GREEN );
Contact contact3 = new Contact( "Nguyen Khuong Dao" , "151250533308" , Color. GRAY
);
Contact contact4 = new Contact( "Vy Van Do" , "161250533207" , Color. YELLOW );
Contact contact5 = new Contact( "Pham Nguyen Hoai Duy" , "151250533113" , Color.
BLACK );
Contact contact6 = new Contact( "Do Thien Giang" , "131250532378" , Color. BLUE );
Contact contact7 = new Contact( "Vo Huu Hai" , "151250533116" , Color. CYAN );

arrContact.add(contact1); arrContact.add(contact2); arrContact.add(contact3);


arrContact.add(contact4); arrContact.add(contact5); arrContact.add(contact6);
arrContact.add(contact7);

CustomAdapter customAdaper = new CustomAdapter( this ,R.layout. row_listview


,arrContact);
lvContact .setAdapter(customAdaper);
}}

And here is the file layout listview_main.xml


<? xml version= "1.0" encoding= "utf-8" ?>
< LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: tools = "http://schemas.android.com/tools"
android :layout_width= "match_parent"
android :layout_height= "match_parent" >

< ListView
android :id= "@+id/lvContact"
android :layout_width= "match_parent"
android :layout_height= "match_parent" />
</ LinearLayout >

In this ListviewActivity create 7 contact objects and then add it to the


Arraylist<Contact> as arrContact to put in the CustomAdapter, then set thatAdapter
on the listView for it to display.

Page 11

You might also like