Listview: Penir Week 5 Teknik Informatika

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

ListView

Penir Week 5
Teknik Informatika
Highlights
• ListView
• Custom ListView
• WebView
ListView
• ListView is a view group that displays a list of scrollable items.
• The list items are automatically inserted to the list using an Adapter
that pulls content from a source such as an array or database query
and converts each item result into a view that's placed into the list.
Method Creating List View
• ListActivity
• Activity with ListView Widget
ListActivity
• The following example uses
ListActivity, which is an activity
that includes a ListView as its
only layout element by default.
• ListActivity is special kind of
activity that doesn't have any
layout attached to it
Tutorial #1
ListActivity
Step 1
• Create blank empty activity Change default extends
class to ListActivity

Delete this selected


codes. Why?
Step 2
Array of string as data
• Prepare data and adapter

val os = arrayOf("Gingerbread", "Honeycomb", "Ice Cream Sandwich", "Jelly Bean", "KitKat",


"Lollipop", "Marshmallow", "Nougat", "Oreo", "Pie")

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)

val arrayAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, os)


listAdapter = arrayAdapter
}

Prepare adapter
ArrayAdapter
• ArrayAdapter is an object than can converts an ArrayList of objects
into View items loaded into the ListView container.
• ArrayAdapter can accept several form of data sources:
• Array of String
• Array of objects
• ArrayList
• List
• etc
• ArrayAdapter usually used with listview and spinner widget
Step 3
• Type onListItemClick … , use arrow up/down to select from
autocomplete suggestion and then press enter
Step 3

Chosen item index

Grab from Array of


String
Tutorial #2
Activity With ListView Widget and array of Object as data source
Activity With ListView
• Use basic activity
• Add ListView widget into its layout
• You can add other widget too
Step 1
Create new activity and with layout like this ->
EditText have ID “txtSearch”
ListView have ID “lstOs”
ListView must be attached to the top, left, right,
and bottom
ArrayAdapter With Array of Object
• In tutorial 1 we simply put array of String
• Can we achieve same thing with array of Object?
• The answer is Yes!
Step 2
• We have to create a class first
• Right click on package name, choose New Kotlin File/Class
• Choose class from combo box and Set “OperatingSystem” as class
name
Step 2

class OperatingSystem(OS:String, apilevel:Int ) {


}
Step 3
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Prepare array of
setContentView(R.layout.activity_main2)
OperatingSystem
objects
var os = arrayOf(OperatingSystem("Gingerbread", 9),
OperatingSystem("Honeycomb", 11),
OperatingSystem("Ice Cream Sandwich", 14),
OperatingSystem("JellyBean", 16),
OperatingSystem("KitKat", 19),
OperatingSystem("Lollipop", 21))
}
Step 4: Prepare Adapter
var os = arrayOf(OperatingSystem("Gingerbread", 9),
OperatingSystem("Honeycomb", 11),
OperatingSystem("Ice Cream Sandwich", 14),
OperatingSystem("JellyBean", 16),
OperatingSystem("KitKat", 19),
OperatingSystem("Lollipop", 21)
)

val arrayAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, os)


lstOs.adapter = arrayAdapter
Step 4: Prepare Adapter
val arrayAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, os)
lstOs.adapter = arrayAdapter

Overall codes look pretty similar compared to tutorial


#1, the only differences is the adapter must directly
attached to the listview widget on activity layout.

lstOs is the ID name of ListView in layout


Run Your App!
• Don’t forget to change MAIN
intent-filter location in manifest to
your new activity
• Notice something wrong here?
Weird String Appear
• This happen because by default
Android will call toString() method of
OperatingSystem object to render
listview data
• Which we haven’t created yet, so
Android will call parent class’
toString()
• That's why weird string here is String
representation of parent Object
Step 5: Add toString
• Go back to OperatingSystem class
• add toString override method:
class OperatingSystem(OS:String, apilevel:Int ){
var OS = OS
var apilevel = apilevel

override fun toString(): String {


return "$OS ($apilevel)"
}
}
Run Again!
Now listview render “OS name” + “apilevel” as
already specified on toString() OperatingSystem class

Perfect!
Challenge!
Make the listview searchable via edittext search!

Hints:
• String “contains” method can search char
sequence
• addTextChangedListener will detect content
changed within edit text
Step 6: Add Touch Listener
val arrayAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, os)
lstOs.adapter = arrayAdapter

lstOs.setOnItemClickListener { parent, view, position, id ->


toast(os[position].OS)
}

Access array of
OperatingSystem object and
display its OS name
Tutorial #3:
Custom ListView
Custom List View
• The ListView instance calls the
getView() method on the
adapter for each data element.
• In this method the adapter
creates the row layout and
maps the data to the views in
the layout.
Custom List View
• An adapter manages the data model and adapts it to the individual
entries in the widget.
• Every line in the widget displaying the data consists of a layout which
can be as complex as you want.
Step 1
• Create new layout. Right click on res > layout and then pick new >
layout resource file
• Name it “listview_layout”
Step 2 ConstraintLayout
layout_width = match_parent
layout_height = wrap_content
• Create Layout similar like this:

Image ID = imgLogo
Image width & height = 70dp
JudulOS ID = txtJudul
ApiLevel ID = txtApi
Steps 3
• Download set of OS images from Classroom
• Copy and paste all images to drawable
• Choose “drawable” and then press OK
• drawable folder used by
android API < 24
• drawable-v24 used by android
API >= 24
Steps 4
class OperatingSystem(OS:String, apilevel:Int, imageid:Int ){
var OS = OS
var apilevel = apilevel
var imageid = imageid add new imageid
filed. This field is used
to store resource
override fun toString(): String { image id
return "$OS ($apilevel)"
}
}
Steps 5
Adjust your array of objects:
var os = arrayOf(OperatingSystem("Gingerbread", 9, R.drawable.gingerbread),
OperatingSystem("Honeycomb", 11, R.drawable.honeycomb),
OperatingSystem("Ice Cream Sandwich", 14, R.drawable.icecream),
OperatingSystem("JellyBean", 16, R.drawable.jellybean),
OperatingSystem("KitKat", 19, R.drawable.kitkat),
OperatingSystem("Lollipop", 21, R.drawable.lollipop)
)
Steps 6
• Create new class, name it “CustomAdapter”
• Set extend to “ArrayAdapter” class. In Kotlin we use ‘:’ to extend a class
class CustomAdapter(val thiscontext: Context,
val os: ArrayList<OperatingSystem>)
: ArrayAdapter<OperatingSystem> (thiscontext,R.layout.listview_layout, os ) {

}
ArrayAdapter is flexible. It This is the custom layout
can handle simple data that have been created
types or object. previously
Next Steps
• Override getView
• Inflate listview_layout
• Update image and text view
Steps 7: Override getView
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val inflater = thiscontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)
as LayoutInflater

}
function getView always get called everytime
data rendered on screen, and its called as
much as the number of data inside array.

getView is perfect place to do custom


layouting

the inflater object is used to inflate layout and


return it in the form of View object
Steps 7: Getting References to Widget
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val inflater = thiscontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)
as LayoutInflater
val v = inflater.inflate(R.layout.listview_layout, parent, false)
val logo = v.findViewById<ImageView>(R.id.imgLogo)
val t = v.findViewById<TextView>(R.id.txtJudul)
val a = v.findViewById<TextView>(R.id.txtApi)

} Getting references to the


widget must be done
manually like this.
Steps 7: Update Widget
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val inflater = thiscontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)
as LayoutInflater
val v = inflater.inflate(R.layout.listview_layout, parent, false)
val logo = v.findViewById<ImageView>(R.id.imgLogo)
val t = v.findViewById<TextView>(R.id.txtJudul)
val a = v.findViewById<TextView>(R.id.txtApi)
logo.setImageResource(os[position].imageid)
t.text = os[position].OS
a.text = os[position].apilevel.toString()
return v
Change widget content
based on array source
}
Step 8: Setting Up Adapter on Activity
• Open Activity again, and make some adjustment

val arrayAdapter = CustomAdapter(this, os.toCollection(ArrayList()))


lstOs.adapter = arrayAdapter

Instead of using generic


toCollection is used to
ArrayAdapter, we know
convert from Array to
use our CustomAdapter
ArrayList
that can handle flexible UI
Output
WebView
• WebView is a view that display
web pages inside your
application.
• You can also specify HTML string
and can show it inside your
application using WebView.
• WebView makes turns your
application to a web application.
Steps
• Create new layout
• Add WebView widget into the
layout
• Set both width and height of
webview to “match_constraint”
• Don’t forget to set webview id
Steps
• In activity, use loadUrl() to load website from external URL
Steps
• By default, WebView disables JavaScript
• Add following code to enable it
Steps
• Since webview try to load external url, you have to write permission
in manifest.xml

<uses-permission
android:name="android.permission.INTERNET" />
Exercise
• Use webview to load Ubaya
website
• Make it fullscreen! (hide action
bar and status bar)
Any QUESTIONS?

You might also like