0% found this document useful (0 votes)
9 views45 pages

Week 4 Toolbar and Menu

This document covers the implementation of toolbars and menus in Android mobile application development, including how to manually add a Material Toolbar and define menus using XML. It discusses event handling for various UI components such as checkboxes, radio buttons, spinners, and pickers, along with examples of context menus and alert dialogs. The document provides code snippets and best practices for managing user interactions and displaying options within an app.

Uploaded by

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

Week 4 Toolbar and Menu

This document covers the implementation of toolbars and menus in Android mobile application development, including how to manually add a Material Toolbar and define menus using XML. It discusses event handling for various UI components such as checkboxes, radio buttons, spinners, and pickers, along with examples of context menus and alert dialogs. The document provides code snippets and best practices for managing user interactions and displaying options within an app.

Uploaded by

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

Week 4:

Toolbar & Menu


CET3013: MOBILE APPLICATION DEVELOPMENT
Today's
Topics
 Toolbar
 Menus
 Options for User
 Choices…
Toolbar
Prior to the Android Studio Flamingo, the default
AppBar will be given under the themes.xml file.

Can set tool bar inside “theme”


Toolbar
No default toolbar was given in Android Studio Flamingo
version because the default parent theme is set as below:

We have to add the Material Toolbar manually instead of


using the default AppBar.
Toolbar
Add the MaterialToolbar to the activity_main.xml.
Toolbar
Add and display the Toolbar by calling the activity’s
setSupportActionBar() method.
If already use view binding, then no need to use findViewById already

Find the toolbar then only pass the toolbar


 Toolbar use to perform actions
Menus
 Menus don't fit so neatly on a smartphone or
table as they do on a desktop, but they are still
useful.
 Android provides two main types of menu:
 Options Menu
 Context Menu
Context menu means when we right Icon title
click, it will show “copy” / “select” / ….
The Options Menu
 The way in which the Options menu appears depends on
the version of Android in use.
 Android devices running Android 2.3 or lower had a
hardware menu buton.
 Pressing this displayed an icon menu with up to 6 items
 If there are more than 6 items there will be a “More” buton which when
tapped displays the expanded menu.
 Current Android devices don't have a hardware menu
button.
 Menu items are added to the Action Bar or ToolBar
 8 but
Normally they are displayed as an overflow item, three vertical dots,
you can change this.
Defining Menus

 Best practice is to define menus in an XML menu


resource file.
 The default “Android Application Project”
already has such a file, with one entry.
<menu xmlns:android="ht
tp://schemas.android.com/apk/res/android" >

<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/action_settings
"/>

</menu>
Showing the Menu

 To associate a menu with an Activity, the Activity must


override onCreateOptionsMenu(Menu menu).
 The Activity that the wizard creates for you already does this.
 The menu is in the file res/menu/main.xml.

override fun onCreateOptionsMenu(menu: Menu?):


Boolean {
Which menu I want to load Parameter
menuInflater.inflate(R.menu.options_menus, menu) initialize
return true the menu
}

To display menu, need to override, or else the option menu will not display
Menu Resource Files
The root element has the tag <menu>.
– As always it must declare the xmlns:android atribute.
Items have the tag <item>.
Items can have the following atributes:
– android:id
● As before, it lets us refer to the menu resource in

code.
android:title
The text that is displayed for the menu

item.

android:icon
Reference to a Drawable resource to provide an icon for the

item.

android:showAsActio
Determines whether the menu item can appear in the Action Bar rather than the overflow

n item.
Menus: Event Handling

 There is one event handler for all menu “click” events. Your
After the user click on the option, what action
Activity needs to override should be perform
 onOptionsItemSelected(item:MenuItem)
 You can find which item it was by using the itemId
attribute of a MenuItem.
 This is a Boolean method.
 If you handle the menu event, you should return true.
 Otherwise, return the superclass implementation of the method.
Menu Example: Resource File

<?xml version="1.0" encoding="utf-8"?>


<menu xmlns:android="
http://schemas.android.com/apk/res/android">
<item android:id="@+id/new_game"
android:icon="@drawable/ic_new_ga
me"
android:title="@string/new_game"
android:showAsAction="ifRoom"/>
<item android:id="@+id/help"
android:icon="@drawable/ic_help"
android:title="@string/help"
/>
always  means always display outside
</menu>
never  the icon will be hidden, only I click the hambager icon ( 三條橫線的 ) then only it will
show out
Menu Example: Event Handling

override fun onOptionsItemSelected(item: MenuItem): Boolean {


when (item.itemId) {
R.id.menu_dialog1 -> showDialog1()
R.id.menu_dialog2 -> showCustomDialog()
R.id.menu_date -> showDateDialog()
R.id.menu_time -> {}
R.id.menu_close -> showCloseDialog()
}
return super.onOptionsItemSelected(item)
}
Context Menus

 Associated with Views.


 Any View can be used, but most ofen used
with a ListView or GridView to provide actions
for each item in the View.
 If you wish to support earlier versions of
Android, you must create a floating context
menu.
When I hold a menu, it will come out another menu that show do you want to edit, delete,
update
And when I hold on the particular menu again eg. Edit, a new menu will come out again eg.
Copy, paste,…
Example Context Menu
Creating a Context Menu

Call registerForContextMenu(), passing the View


concerned as a parameter.
– If you're using a ListView (e.g.) and want the menu to
be available for all items, then pass the ListView itself as
the parameter.
Override onCreateContextMenu() in your
Activity.
Override onContextItemSelected() to handle menu
item selection.
Context Menu Creation

 Need to call the superclass implementation of


the method.
 Otherwise prety similar to the creation of
an options menu.

override fun onCreateContextMenu(


menu: ContextMenu?,v: View?,
menuInfo: ContextMenu.ContextMenuInfo?) {
super.onCreateContextMenu(menu, v, menuInfo)
menuInflater.inflate(R.menu.float_contextual_menu,
menu)
}
Context Menu Event Handling

//handling click events in an float context menu items clicks


override fun onContextItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.color -> {
var textView = findViewById<TextView>(R.id.textHappyCoding)
textView.setTextColor(Color.parseColor("#FF0000"))
Toast.makeText(this, "color changed", Toast.LENGTH_SHORT).show()
return true
}
else -> {
return super.onContextItemSelected(item)
}
}
}
CheckBox
Checkboxes let the user select one or more options
from a set.
 Detect its state (checked or unchecked).
CheckBox
Checkboxes let the user select one or more options
from a set.
 Detect its state (checked or unchecked).
CheckBox - Layout
CheckBox Event Handling
RadioButtons
 Radio buttons allow the user to select one option
from a set.
You must group them together inside a RadioGroup.
By grouping them together, the system ensures that
only one radio button can be selected at a time.
RadioButtons - Layout

|
|
|
|
|
radioButtons | Need to implement the onRadioButtonClicked,
inside | then check whether it is clicked or not
radioGroup |
|
|
|
|
|
RadioButton Event Handling 1
Like this:
RadioButton Event Handling 2
But this is more preferred: implement into radioGroup
Spinners
Quick way to select one value from a set.
In the default state shows currently selected
value.
Touching displays a dropdown menu available
values
Spinners Resources
The choices you provide for the spinner can come
from any source
 string arrays in strings.xml resource file.
Normally works with SpinnerAdapter or
ArrayAdapter.
Optional way by using the entries attributes.
Spinners Resources
<?xml version="1.0"
encoding="utf-8"?>
<resources>
<string-array
name="planets_array">
<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>
Spinner - Layout
<Spinner
android:id="@+id/contact_plannet"
android:layout_width="match_parent"
android:layout_height="wrap_content“
android:entries =
“@array/planets_array” />
Spinner – Event Handling
val spinner = findViewById<Spinner>(R.id.spinner)
val planets = resources.getStringArray(R.array.planets_array)
val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, planets)
Send the adapter to here

Send the planets to here by using


spinner.adapter = adapter Set adapter getStringArray (set in last slide)
spinner.onItemSelectedListener = object :
AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>,
view: View, position: Int, id: Long) {
// write code to perform some action
}

override fun onNothingSelected(parent: AdapterView<*>) {


// write code to perform some action
}
}
Pickers
Like Spinners but are ready-to-use dialogs
Well known pickers include
o Date Picker
o Time Picker (eg. use in doctor appointment)
o Number Picker

Both Pickers and Spinners constrain User Input


o Excellent way to limit errors
Number Picker
Ideal for range restricted
numerics
Simple XML from Designer
Need to set
setOnValueChangedListener

<NumberPicker android:id="@+id/numberpicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Number Picker Event Handling
numberPicker.minValue = 0
numberPicker.maxValue = 10

numberPicker.wrapSelectorWheel = true

numberPicker.setOnValueChangedListener { picker, oldVal, newVal ->


val text = "Changed from $oldVal to $newVal"
Toast.makeText(this@MainActivity, text,
Toast.LENGTH_SHORT).show()
}
DatePicker
 Android DatePicker is a user interface control
which is used to select the date by day, month
and year in our android application.
 We recommend that you use DialogFragment
to host each time or date picker.
o The DialogFragment manages the dialog lifecycle for
you and allows you to display the pickers in different
layout configurations
DatePicker - Layout

Direct put inside the layout, but


seldom do this
We normally put it inside a button
(after click the button then only it
will show and let user choose)
DatePicker Event Handling
val datePicker = findViewById<DatePicker>(R.id.date_Picker)
val today = Calendar.getInstance()

datePicker.init( today.get(Calendar.YEAR),
today.get(Calendar.MONTH),
today.get(Calendar.DAY_OF_MONTH))
{ view, year, month, day ->

val month = month + 1


val msg = "You Selected: $day/$month/$year"
Toast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show()
}
DatePicker – Using
DialogFragment Part 1
class DatePickerFragment : DialogFragment(), DatePickerDialog.OnDateSetListener {

override fun onCreateDialog(savedInstanceState: Bundle): Dialog {


// Use the current date as the default date in the picker
val c = Calendar.getInstance()
val year = c.get(Calendar.YEAR) Normally use DialogFragment and override it
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)

// Create a new instance of DatePickerDialog and return it


return DatePickerDialog(requireContext(), this, year, month, day)

override fun onDateSet(view: DatePicker, year: Int, month: Int, day: Int) {
// Do something with the date chosen by the user
}
}
DatePicker – Using
DialogFragment Part 2
 Showing DatePicker with the DialogFragment

fun showDatePickerDialog(v: View) {


val newFragment = DatePickerFragment()
newFragment.show(supportFragmentManager,
"datePicker") This is fix already, always use this Retrieve back the
} datePicker, anything also
can put
TimeDialog
 Android TimePicker is a user interface control for selecting the
time in either 24-hour format or AM/PM mode.
TimeDialog
 Using the setOnTimeChangeListener to
adjust the time frame.

val timePicker = findViewById<TimePicker>(R.id.timePickers)

timePicker.setOnTimeChangedListener { _, hour, minute -> var hour = hour

val msg = "Time is: $hour : $min $am_pm"


textView.text = msg
textView.visibility = ViewGroup.VISIBLE
}
Alert Dialogs
Creating a dialog
◦ All of AlertDialog’s constructors are protected.
◦ What to do?
◦ Use AlertDialog.Builder.
◦ Should be created in an ovveride of the Activity method
onCreateDialog(int).
Showing a dialog
◦ Call showDialog(int), passing the ID of the dialog you want to show.

AlertDialog.Builder 
Negative button
Neutral button  no action will be performed
Eg. Maybe ( 不確定的時候選的 ) Positive button
Alert Dialogs Example
val builder = AlertDialog.Builder(this)
builder.setTitle("Androidly Alert")
builder.setMessage("We have a message")
//builder.setPositiveButton("OK", DialogInterface.OnClickListener(function = x))

builder.setPositiveButton(android.R.string.yes) { dialog, which ->


Toast.makeText(applicationContext,
android.R.string.yes, Toast.LENGTH_SHORT).show()
}
builder.setNegativeButton(android.R.string.no) { dialog, which ->
Toast.makeText(applicationContext,
android.R.string.no, Toast.LENGTH_SHORT).show()
}
builder.setNeutralButton("Maybe") { dialog, which ->
Toast.makeText(applicationContext,
"Maybe", Toast.LENGTH_SHORT).show()
}
builder.show()
Summary
Toolbar
Menus
Radio buttons, Check boxes
Pickers

You might also like