0% found this document useful (0 votes)
16 views51 pages

AdvNative Week 3 - Navigation Part 2

Uploaded by

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

AdvNative Week 3 - Navigation Part 2

Uploaded by

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

NAVIGATION

(part 2)

WEEK 3
Advanced Native Mobile Programming
1604C062

Informatics Engineering - Universitas Surabaya


HIGHLIGHTS
● popUpTo & popUpToInclusive
● Navigation Component with BottomBar Navigation
● Navigation Component with Dialog
● Navigation Component with Drawer

Please re-open previous


week project to follow this
week tutorial
PopUp
popUpTo & popUpToInclusive
POPUP
Lets start with an example

Two fragments. Main can navigate


to game fragment, vice versa.
POPUP
MainFragment serves as the “default” or “main” fragment

The initial backstack


only have one
fragment (main)

MainFragment

BackStack
POPUP
Player then presses start button (navigate to game fragment)

Now backstack
contain two
fragments. What
happen if back
button is pressed?

Game Fragment

MainFragment

BackStack
POPUP
Player presses back button (soft) or hard or call navigate codes

The default behavior is a


new instance of
destinations fragment
created. Now backstack
contains three
fragments with two
MainFragment instances of
MainFragment
Game Fragment

MainFragment

BackStack
POPUP
And then player presses start button (navigate to game fragment)

Another instance of
GameFragment
created on backstack.
Game Fragment How to change this
behavior?
MainFragment

Game Fragment

MainFragment

BackStack
USING POPUPTO
popUpTo attributes can be applied to an action (arrow) to remove
backstack content until it reaches the destination fragment

example:

Let’s say there are three


fragments currently on the
backstack. Next from
fragment C it can navigate
Fragment C to Fragment A

Fragment B

Fragment A
USING POPUPTO
Using popUpTo fragmentA, it will popup every item on backstack
until it reaches the destination (fragmentA)

Fragment C

Fragment C & B are


popped out from
Fragment B backstack. Fragment A
remains active on
Fragment C backstack

Fragment B

Fragment A
LET’S TRY IT

Open your navigation graph, click arrow (action) from game


fragment to main fragment. Change the popUpTo attributes to
mainFragment
USING POPUPTOINCLUSIVE
popUpToInclusive attributes will remove each stack object until it
reaches the destination, including the destination itself

Fragment C

Fragment A is also popped


out of the backstack.
Fragment B Android will create a new
instance of Fragment A.
Fragment C This is useful if you need to
get latest data to fragment
Fragment B A (from server maybe?)
Fragment A
Fragment A
BottomBar
With navigation component
BOTTOM BAR NAVIGATION
Previously in Native course, you
need at least three things:
ViewPager, BottomBar Navigation,
Kotlin codes that manually handle
the navigation
BOTTOM BAR WITH NAV
COMPONENT
First we need three icons for bottom bar navigation.

Right click on res > new > Vector assets, and then create three icons:

home list person


FRAGMENTS
Each bottom bar icon will navigate to its respective fragments

= MainFragment

= HistoryFragment

= ProfileFragment
CREATE FRAGMENTS
Create two new fragments, name them
HistoryFragment and ProfileFragment

Make sure you follow similar steps in


week 2 to cleanup codes in fragment
class

For each fragment, set the layout like


screenshot on the right
CREATE BOTTOM MENU RESOURCE
Next step is creating bottom bar menu resource file

1. Right click on res > new > Android resource file


2. Fill in file name to “bottom_menu”
3. Choose resource type as “menu” (this will generate menu folder
within res)
4. Press OK
CREATE BOTTOM MENU RESOURCE
1. Drag three Menu Items and set attributes as indicated here:
2. Home Icon
4. Profile Icon
a. Id = itemHome
a. Id = itemProfile
b. Icon = drawable home
b. Icon = drawable person
c. showAsAction = always
c. showAsAction = always
d. Title = home
d. Title = profile
3. History Icon
a. Id = itemHistory
b. Icon = drawable list
c. showAsAction = always
d. Title = history
ADD BOTTOM NAVIGATION
Next step is adding bottom navigation to MainActivity layout

1. Open activity_main.xml
2. Drag and drop BottomNavigationView component
3. Change id to “bottomNav”
4. Set menu to “@menu/bottom_menu”
5. Set layout_width = match_constraint
6. Set layout_height = wrap_content
7. Constrained to very bottom of screen
ADD BOTTOM NAVIGATION
UPDATE NAVIGATION GRAPH
Next step, we should update navigation graph by adding new
destinations (fragment profile and history). Open game navigations
and add two destinations
!! IMPORTANT !!
To create a connection between navigation controller with
navigation bar you need to set same ID on both of Destinations
Object and Menu Item ID
!! IMPORTANT !!
It means that for MainFragment destinations you should rename
the id as “itemHome”
!! IMPORTANT !!
This dialog shows that the id already exists. Just press continue to
ignore this warning.
NO ACTION/ARROW
For this case, its unnecessary to draws connection/arrow between
those fragments. Bottom bar navigation allows user to jump in
various fragment without specific flow order.
ESTABLISH CONNECTION
Final step is to establish connection between nav controller and the
bottom bar. Remember: nav controller holds navigation host that
relies on navigation graph.

Open main activity, add following codes inside onCreate method:

var bottomNav = findViewById<BottomNavigationView>(R.id.bottomNav)


bottomNav.setupWithNavController(navController)
RESULTS
Try to click different menu
Dialog
With navigation component
DIALOG
Previously in Native course, you use
AlertDialog builder or custom
dialog fragment to show a dialog
DIALOG FRAGMENT
First step, of course we need dialog fragment. Create a new fragment
and set name as OptionFragment

Extend the fragment class to


class OptionFragment : BottomSheetDialogFragment() {

BottomSheetDialogFragment just fundamentally acts as regular


dialog, but will slide up from bottom screen (with animation)
Because the textinputlayout
DIALOG FRAGMENT LAYOUT mode set to dropdown, you
need to change the TextView
Create layout based on reference below with the
AutoCompleteTextView.
Delete the original TextView
and replace with the
AutoCompleteView

txtInputLayout
endIconMode = dropdown_menu
DIALOG FRAGMENT LAYOUT
ConstraintLayout parent
- Layout_width =
match_parent
- Layout_height =
wrap_content

Set bottom constrained for the


Three checkboxes
UPDATE NAVIGATION GRAPH
Open navigation graph, add dialog
optionFragment as new destination

Draw arrow/actions from itemHome (main


Fragment) to optionFragment

As usual rename actions as


“actionOptionFragment”

Don’t create opposite arrow from


optionFragment, because dialog should
close itself if user tap on outside of dialog
body
ADD OPTIONS BUTTON
● To invoke the dialog, we need a button in main fragment layout.
● This time we use Material3 button icon
● Add the icon by create new vector asset. Find the “settings” icon.
● Drag and drop the button and constrained on the upper right of
the screen
● Change the “style” properti to
@style/Widget.Material3.Button.IconButton.Outlined
● Set id to btnOption
● Change the “icon” properti
TRIGGER THE DIALOG
To trigger the dialog, it doesn't requires alert dialog. Use the same
method like navigating to other screens

In MainFragment.kt (onViewCreated), add following codes

val btnOption = view.findViewById<Button>(R.id.btnOption)


btnOption.setOnClickListener {
val action = MainFragmentDirections.actionOptionFragment()
Navigation.findNavController(it).navigate(action)
}
RESULT
Click option button

The dialog should appear from bottom screen

Click on outside of dialog body to close the


dialog
CREATE DROPDOWN VALUE
Back to the OptionFragment, create following static array:
private val LEVEL = arrayOf("Easy", "Medium", "Hard")

And initilaize the AutoCompletTextView inside the onViewCreated


override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val adapter:ArrayAdapter<String> = ArrayAdapter<String>(requireContext(),
android.R.layout.simple_dropdown_item_1line, LEVEL)
val txtLevel = view.findViewById<AutoCompleteTextView>(R.id.txtLevel)
txtLevel.setAdapter(adapter)
}
Drawer
With navigation component
NAV DRAWER
Previously in Native course, you
must implement navigation
manually for each menu items on
drawer
NAVIGATION DRAWER
Navigation drawer can co-exist with bottom navigation

To create a navigation drawer, the first step is to wrap your layout


under DrawerLayout component

This need to be done manually, in XML codes

Note: please refer to Native course for more information about


drawer layout
NAVIGATION DRAWER
Open activity_main.xml, click on button to switch view from
design to XML codes. Write following codes at the top of the layout.

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


<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android" Cut paste these
xmlns:app="http://schemas.android.com/apk/res-auto" three xml codes
from Constraint
xmlns:tools="http://schemas.android.com/tools" layout tags
android:id="@+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" This drawer layout
id is “drawerLayout”
android:fitsSystemWindows="true">
NAVIGATION DRAWER
<androidx.drawerlayout.widget.DrawerLayout . . .>

<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent" Wrap constraint
layout within drawer
tools:context=".MainActivity"> layout tags
....
</androidx.constraintlayout.widget.ConstraintLayout>

</androidx.drawerlayout.widget.DrawerLayout>
Enclosed drawer
layout tag
NAVIGATION VIEW
Switch back to design view, drag and drop a navigation view
component, and arrange it like following screenshot

Navigation View
● Id = navView
● layout_gravity =”start”
● layout_width = wrap_content
● layout_height = match_parent
● Menu = @menu/bottom_menu
IMPORTANT! Navigation
View must be placed on
the bottom of layout. Not
under Constraint layout
NAVIGATION VIEW
Notice that navigation view is using the same menu resource files as
bottom navigation bar.

It means that the drawer will render the same menu structure and
item as the navigation bar. Therefore, no need to update navigation
graph.

Of course you can create separate menu for the drawer

For simplicity purpose, we


don't use a navigation
header during the tutorial
ESTABLISH CONNECTION
Final step is to establish connection between drawer & navigation
view to navigation controller

Open MainActivity.kt, write following codes:

class MainActivity : AppCompatActivity() {


private lateinit var navController: NavController
private lateinit var drawerLayout: DrawerLayout
Navigation view also
need to be handled by
NavController
ESTABLISH CONNECTION
Write following codes under onCreate:
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
drawerLayout = findViewById(R.id.drawerLayout)

navController = (supportFragmentManager.findFragmentById(R.id.hostFragment)
as NavHostFragment).navController

NavigationUI.setupActionBarWithNavController(this, navController, drawerLayout)

val navView = findViewById<NavigationView>(R.id.navView)


NavigationUI.setupWithNavController(navView, navController) This refer to
drawer layout
component
. . . Navigation view also
need to be handled by
NavController
ESTABLISH CONNECTION
Update onSupportNavigateUp method:

override fun onSupportNavigateUp(): Boolean {


return NavigationUI.navigateUp(navController, drawerLayout)
|| super.onSupportNavigateUp()
}
Previously this set
to null (without
drawer)
This code automatically detects if
the user is on the top level of
backstack: the drawer icon will
show instead of the back button
RESULT

Navigation Controller automatically


handles item click navigation

If user is not in top level of backstack


then back icon will displayed

Remember that you must use same


id both for navigation graph
destinations and menu item
THANKS!
DO YOU HAVE ANY QUESTION?

[email protected]

CREDITS: This presentation template was


created by Slidesgo, including icons by
Flaticon, infographics & images by Freepik.

Please keep this slide for attribution.

You might also like