banner



How To Register Custum Class In Androidmanifest.xml

Among other goodies, Android Jetpack comes with the Navigation architecture component, which simplifies the implementation of navigation in Android apps.

In this tutorial, you'll add navigation to a uncomplicated book-searching app and acquire nigh:

  • Navigation graphs and nested graphs.
  • Actions and destinations.
  • How to pass data between destinations.
  • The NavHost interface.
  • Creating deep links.

The Navigation architecture component is still in early on development, but it is already proving to be a powerful and handy tool, equally you lot will see for yourself.

Note: This tutorial assumes yous know the nuts of Android development with Kotlin. If y'all are new to Kotlin, bank check out our Kotlin introduction tutorial. If you are new to Android development, cheque out our Android Tutorials first.

Why Practise Y'all Need Notwithstanding Another Component?

Navigating between screens — passing information, handling the back stack, implementing deep links, etc. — tin be complicated. It also comes with quite a bit of boilerplate. To top it off, you should attach to the new principles of navigation:

  • The app should have a fixed offset destination.
  • A stack is used to represent the navigation state of an app.
  • The Up button never exits your app.
  • Up and Back are equivalent within your app's job.
  • Deep linking to a destination or navigating to the same destination should yield the same stack.

By using the Navigation architecture component, you provide a consistent and predictable experience to users — hassle and boilerplate free.

Getting Started

To use the Navigation compages component, y'all must utilize Android Studio 3.ii or higher. Install it by following the instructions in our Beginning Android development tutorial. Brand certain to install the latest stable release.

Next, download the materials for this tutorial using the Download materials push button at the top or bottom of the tutorial.

Open Android Studio and import the starter project with File ▸ Open up. Discover the location where you lot extracted the starter project, highlight the root folder of the starter projection, and click Open. The sample project is named Bookmans Treasure. Once the project is synced, build and run it.

Starter project

If you run across a blank screen, you lot're on the right track.

Adding the Navigation Architecture Component

Open the build.gradle file in the app binder and add together the following to the dependencies block:

implementation "android.arch.navigation:navigation-fragment-ktx:1.0.0-alpha05" implementation "android.arch.navigation:navigation-ui-ktx:ane.0.0-alpha05"        

Wondering about the -ktx suffix in the library names? Information technology signifies the Android KTX libraries that are super dainty to use with Kotlin by making your code both more concise and readable.

Sync the project. Then build and run the app over again.

Starter project with dependency added

Information technology's still blank, but hold tight — y'all are now ready to start working on the screen navigation.

Navigation Graph

A set of destinations and actions etch an app'south navigation graph:

Navigation graph

The above represents the navigation graph for the Bookmans Treasure app. Nodes represent the screens and arrows show how you navigate betwixt them.

You lot'll add the navigation graph to the app now.

Y'all must kickoff enable the Navigation Editor. Click File ▸ Settings (or Android Studio ▸ Preferences on Mac), choose the Experimental category in the left panel, cheque Enable Navigation Editor:

Enable Navigation Editor

Click OK and and then restart Android Studio.

Now exist certain Android is selected in the Projection navigator.

Android panel

Click on the res folder, press command+N (on Mac) or Alt+Due north (on PC) (or File ▸ New) and select Android Resource File.

New Android resource file

A dialog to create a new resource will pop up. Nether File proper name, enter nav_graph. Under Resources type, select Navigation:

Navigation Resource file

Click OK.

Android Studio will create a new resource directory called navigation with a new file named nav_graph.xml. This is where your navigation graph will live.

New file created

Opening nav_graph.xml, yous tin toggle between the Text editor and the Navigation editor by clicking the tabs at the bottom of the editor window.

Navigation editor

Click on the Text tab to open the XML editor.

Destinations

Each destination represents a screen you can navigate to. By default, the Navigation architecture component includes support for Activities and Fragments. You'll learn how to add custom types later in this tutorial.

Add the post-obit between the navigation tags:

<fragment   android:id="@+id/bookSearchFragment"   android:proper name="com.raywenderlich.android.bookmanstreasure.ui.booksearch.BookSearchFragment"   android:label="Book Search Fragment"   tools:layout="@layout/fragment_book_search"> </fragment>        

You might get an error on the tools:layout attribute. To set it, add tools namespace declaration to the navigation tag:

xmlns:tools="http://schemas.android.com/tools"        

Yous can do this manually or place your cursor on tools:layout and press Alt+Enter (on PC) or command+return(on Mac). You'll become a Quick action pop-upward:

Tools namespace

Cull Create namespace declaration.

This makes BookSearchFragment a destination. Fragment destinations accept the post-obit attributes:

  • android:id: A unique resources proper name for this destination.
  • android:name: A fully qualified class name.
  • android:label: The Fragment title.
  • tools:layout: The Fragment layout, rendered by the Navigation editor.

Build and run the app. Getting fed up with the blank screen nonetheless?

Declaring a Offset Destination

Every app needs a starting indicate. To declare a starting destination in the navigation graph, add the following aspect to the navigation tag:

app:startDestination="@+id/bookSearchFragment"        

If the app namespace yields an mistake, follow the same set of steps you used above for the tools namespace to fix it. Build and run to make sure at that place are no errors. Seriously — blank screen, again?

Surprised

You're missing one more thing: the NavHost interface.

NavHost Interface

The NavHost interface enables destinations to exist swapped in and out. The Navigation architecture component provides a default implementation: the NavHostFragment.

Open activity_main.xml layout file located in res/layout. Look for the FrameLayout with ID placeholder and replace it with the post-obit fragment:

<fragment   android:id="@+id/navHostFragment"   android:name="androidx.navigation.fragment.NavHostFragment"   android:layout_width="match_parent"   android:layout_height="match_parent"   app:navGraph="@navigation/nav_graph"   app:defaultNavHost="true" />        

Note the two new attributes:

  • app:navGraph: Specifies which navigation graph will exist associated with the navigation host.
  • app:defaultNavHost: If set to true, the navigation host will intercept the Back push.

To ensure the Back button works properly, you besides need to override the onSupportNavigateUp() method in MainActivity.kt. Paste this clamper of code anywhere in the class:

override fun onSupportNavigateUp() =    findNavController(this, R.id.navHostFragment).navigateUp()        

And add the import statement, if necessary:

import androidx.navigation.Navigation.findNavController        

Now, build and run the project. No more bare screens!

Empty book search

Connecting Destinations

Deportment

Open nav_graph.xml and add a new destination for WorkDetailsFragment:

<fragment   android:id="@+id/workDetailsFragment"   android:proper name="com.raywenderlich.android.bookmanstreasure.ui.workdetails.WorkDetailsFragment"   android:characterization="work_details_fragment"   tools:layout="@layout/fragment_work_details"> </fragment>        

This volition be used to show book details, such as the author name, title, listing of editions, etc.

To navigate between destinations, y'all use deportment. Find the fragment with the bookSearchFragment ID, and paste this within its the fragment tags:

<action  android:id="@+id/actionBookDetails"   app:destination="@id/workDetailsFragment" />        

You can now navigate to WorkDetailsFragment. The two attributes:

  • android:id: The ID uniquely identifying this action.
  • app:destination: The ID of the desired destination.

To ensure the action is triggered, open BookSearchFragment.kt in the ui.booksearch parcel. Expect for the comment:

//TODO implement navigation to Book details        

Replace the TODO with:

findNavController().navigate(R.id.actionBookDetails)        

At the end of the import section, add the following:

import androidx.navigation.fragment.findNavController        

Build and run. Search for a book using a generic word like "after" and tap on one of the results. You'll get a particular folio that is currently blank:

Empty work details

You'll learn how to pass arguments between destinations shortly. First, add more destinations using the Navigation editor.

Navigation Editor

So far, you've added destinations and deportment using XML. Now, you'll become familiar with the Navigation editor. Open thenav_graph.xml file and click on the Pattern tab at the lesser of the editor.

Navigation editor sections

At that place are three sections in the editor:

  1. Destinations list
  2. Graph Editor that shows your navigation graph
  3. Attributes Editor for selected destination or action

Add some other destination to the graph. Click on the icon with the green + sign at the top of the graph editor.

Add destination

Offset typing favorites and select FavoritesFragment from the list.

Nav editor Add dialog

Yous can edit the properties of the new destination using the Attributes editor. Set the ID to favoritesFragment.

Nav Editor ID

In the editor, hover your mouse over the dot on the middle of the correct side of favoritesFragment. Then, printing and concord, and elevate the line to the workDetailsFragment.

Creaing a new action

This creates a new activeness, navigating from FavoritesFragment to WorkDetailsFragment. Make sure the activity (the line with the arrow) is selected in the editor and prepare the activity ID to actionBookDetails.

Nav editor action ID

At present, add another destination, BookDetailsFragment, following the aforementioned steps equally in a higher place. And then, create an action that navigates from workDetailFragment to bookDetailsFragment. Prepare its ID to actionShowEdition. Your nav_graph.xml should look similar this:

Nav graph with book details

Open WorkDetailsFragment.kt in the ui.and supervene upon:

//TODO Implement navigation to edition details        

With:

findNavController().navigate(R.id.actionShowEdition)        

And add the import statement, if necessary:

import androidx.navigation.fragment.findNavController        

Build and run the app to make sure at that place are no errors.

Navigating From a Carte

If you've toggled the navigation drawer, you might have noticed the Favorites menu detail.

App drawer

You can utilise the Navigation architecture component to handle carte deportment as well. Open up MainActivity.kt and supersede:

//TODO setup Navigation Drawer menu item actions        

With:

drawerLayout.navView.setupWithNavController(   navHostFragment.findNavController())        

Add the following at the end of the import list:

import androidx.navigation.fragment.findNavController import androidx.navigation.ui.setupWithNavController import kotlinx.android.synthetic.primary.activity_main.view.*        

The Navigation controller assumes the menu IDs are the same as your destination IDs and therefore knows what to do when an item is selected.

Build and run the app. Open the navigation drawer and tap on Favorites:

App Favorites

How easy was that? You tin return back to the Book Search using either the dorsum button or the navigation drawer.

Passing Information and Animating Actions

Passing Data Betwixt Destinations

You often need to laissez passer information betwixt your destinations. Remember @+id/actionBookDetails you added before?
Currently, information technology opens the right screen but shows no details for a selected volume. You'll ready this, now.

Go back to the BookSearchFragment and find the phone call to findNavController().navigate(R.id.actionBookDetails). Replace information technology with:

findNavController().navigate(   R.id.actionBookDetails,   WorkDetailsViewModel.createArguments(it) )        

Using a helper method, you passed a Packet instance equally a second argument. Its content will exist used to construct the destination — the WorkDetailsFragment. Yous might need to add the following import:

import com.raywenderlich.android.bookmanstreasure.ui.workdetails.WorkDetailsViewModel        

Note: The it argument is the data class Book, containing general book information. it is the implicit name within a lambda expression with only 1 parameter. Check the documentation to larn more than.

Build and run the app. Search for your favorite book and tap on a search result:

Work details

Now, follow the same fix of steps in WorkDetailsFragment. Find:

findNavController().navigate(R.id.actionShowEdition)        

Replace it with:

findNavController().navigate(   R.id.actionShowEdition,   BookDetailsViewModel.createArguments(it) )        

Add together the import if you need to:

import com.raywenderlich.android.bookmanstreasure.ui.bookdetails.BookDetailsViewModel        

Build and run the app. Search for a book, check its details and select an edition. You should encounter the edition details.

Edition details

Finally, have intendance of the FavoritesFragment. Expect for:

//TODO implement navigation to Piece of work details        

Supersede it with:

findNavController().navigate(   R.id.actionBookDetails,   WorkDetailsViewModel.createArguments(information technology) )        

Every bit before, you might need to add together the import statements:

import androidx.navigation.fragment.findNavController import com.raywenderlich.android.bookmanstreasure.ui.workdetails.WorkDetailsViewModel        

Adding Transitions

You can add custom animations to deportment using attributes in the activity tag. Open up nav_graph.xml. Select the Text tab at the bottom, and add together the following attributes to the actions with ID @+id/actionBookDetails (there are ii such actions):

app:enterAnim="@anim/slide_in_right" app:exitAnim="@anim/slide_out_left" app:popEnterAnim="@anim/slide_in_left" app:popExitAnim="@anim/slide_out_right"        

Each of the new tags defines a custom transition for one of the cases:

  • enterAnim: Resources ID of the blitheness to utilise for the incoming destination.
  • exitAnim: Resources ID of the blitheness to utilise for the outgoing destination.
  • popEnterAnim: Resource ID of the blitheness to utilize for the incoming destination when popping the backstack.
  • popExitAnim: Resources ID of the animation to employ for the outgoing destination when popping the backstack.

Build and run the app. Search for a volume, click on one of the results and see the blitheness in action.

Types of Destinations

The Navigation architecture component supports Activities and Fragments out-of-the-box, simply you lot can also add custom types.

Adding New Destination Types

Check the com.raywenderlich.android.bookmanstreasure.ui.authordetails packet. The AuthorDetailsDialog class tin show the author details. Yous'll put it to apply and add back up for DialogFragment destinations.

To add a custom destination, you have to implement the Navigator interface. You pass it to the NavigationController when initializing the navigation graph.

First, create a new package at the root level called destinations, by clicking on the com.raywenderlich.android.bookmanstreasure parcel in your project explorer, and so press command+Due north (or File ▸ New) and select Package.

New package

Type "destinations" in the dialog and click OK.

New package dialog

Click on the new package and then press command+N (or File ▸ New) and select Kotlin File/Class.

New file

Nether name, enter AuthorDetailsNavigator and click OK.

New file name

Add together the following code in the new file:

import android.bone.Bundle import androidx.navigation.NavDestination import androidx.navigation.NavOptions import androidx.navigation.Navigator  // 1 @Navigator.Name("author") class AuthorDetailsNavigator : Navigator<AuthorDetailsNavigator.Destination>() {    // 2   override fun navigate(destination: Destination, args: Package?, navOptions: NavOptions?) {}    // 3   override fun createDestination(): Destination {     render Destination(this)   }    // 4   override fun popBackStack(): Boolean {     return false   }    // 5   class Destination(authorDetailsNavigator: AuthorDetailsNavigator) :       NavDestination(authorDetailsNavigator) }        

Going over this step by step:

  1. Here, you declare the name of the tags that you will use for your custom destinations using the @Navigator annotation. The name is what you will add to the nav_graph.xml file the same mode as yous did for fragment destinations. You also extend the Navigator abstract grade.
  2. navigate() is the Navigator function that performs the navigation to your destination.
  3. This is the role that instantiates your type of destination.
  4. This function navigates back through the back stack. You can ignore it in this case and return faux.
  5. This nested course holds the data for your custom destination. Its job is to parse all attributes in your destination tag and store them.

Adjust the AuthorDetailsNavigator constructor to have a FragmentManager parameter:

class AuthorDetailsNavigator(     private val manager: FragmentManager ) : Navigator<AuthorDetailsNavigator.Destination>() {        

Add together the import argument for the FragmentManager:

import android.support.v4.app.FragmentManager        

Next, replace the empty navigate() function with:

override fun navigate(destination: Destination, args: Bundle?, navOptions: NavOptions?) {   val dialog = AuthorDetailsDialog()   dialog.arguments = args   dialog.bear witness(director, AuthorDetailsDialog.TAG) }        

Import the AuthorDetailsDialog, if required:

import com.raywenderlich.android.bookmanstreasure.ui.authordetails.AuthorDetailsDialog        

The function creates a new case of the AuthorDetailsDialog, sets the Bundle as the dialog arguments and shows it using the FragmentManager.

You now need to tell the Navigation architecture component about your custom destination. Open up the MainActivity form and replace

//TODO initialize navigation graph        

with the post-obit:

val destination = AuthorDetailsNavigator(navHostFragment.childFragmentManager) navHostFragment.findNavController().navigatorProvider.addNavigator(destination)  val inflater = navHostFragment.findNavController().navInflater val graph = inflater.inflate(R.navigation.nav_graph) navHostFragment.findNavController().graph = graph        

You might also need an import statement:

import com.raywenderlich.android.bookmanstreasure.destinations.AuthorDetailsNavigator        

In these additions to MainActivity, aside from calculation your custom destination, you also inflate the nav_graph.xml file yourself. This ensures the custom author attribute name is recognized.

Define an author details destination in nav_graph.xml:

<author   android:id="@+id/authorDetails" />        

Next, add the post-obit activeness for the @+id/workDetailsFragment destination:

<action     android:id="@+id/actionShowAuthor"     app:destination="@id/authorDetails" />        

Open up WorkDetailsFragment and supercede:

//TODO implement navigation to Author details        

With:

findNavController().navigate(   R.id.actionShowAuthor,   AuthorDetailsViewModel.createArguments(it) )        

Add the import statement, too:

import com.raywenderlich.android.bookmanstreasure.ui.authordetails.AuthorDetailsViewModel        

Finally, open activity_main.xml and remove the app:navGraph="@navigation/nav_graph" attribute on the NavHostFragment fragment tag. If yous don't, the app volition crash.

Build and run the app. Search for a book, open up its details and tap on the author proper noun. If a dialog opens, you lot're winning!

Author details dialog

Common Destinations

To reuse actions, you can declare them exterior of any destination tags. Such actions are chosen global actions.

You'll now make showing author details a global action.

Open nav_graph.xml. Move the @+id/actionShowAuthor action from the @+id/workDetailsFragment destination to instead be a direct child of the navigation tag. At present open BookDetailsFragment and replace

// TODO implement navigation to author details        

with the following:

findNavController().navigate(   R.id.actionShowAuthor,   AuthorDetailsViewModel.createArguments(it) )        

Add together the missing import statements:

import androidx.navigation.fragment.findNavController import com.raywenderlich.android.bookmanstreasure.ui.authordetails.AuthorDetailsViewModel        

Build and run your app. Now, yous can open author details from both the Piece of work details and Book edition details screens.

Deep Links

Deep links are URLs that link to a specific screen or content of your app. Your next chore is to create a deep link to the Favorites screen.

Open nav_graph.xml file. Look for the fragment tags with the @+id/favoritesFragment ID, and paste this between its tags:

<deepLink app:uri="bookmanstreasure://habitation/favorites" />        

The Navigation architecture component volition associate the provided URI with the FavoritesFragment. Open AndroidManifest.xml and add the post-obit between the sole activity tags:

<nav-graph android:value="@navigation/nav_graph" />        

Add the code to handle deep links at the terminate of the onCreate() method in MainActivity:

findNavController(this, R.id.navHostFragment).onHandleDeepLink(intent)        

And, finally, add the following implementation of the onNewIntent() method to MainActivity:

override fun onNewIntent(intent: Intent?) {   super.onNewIntent(intent)   findNavController(this, R.id.navHostFragment).onHandleDeepLink(intent) }        

Make sure to also add together the import statement:

import android.content.Intent        

Rebuild the app and open the AndroidManifest.xml file. Click on the Merged Manifest tab at the lesser of the editor. You'll discover that the Navigation architecture component has been added a few items:

Generated manifest

To exam deep links, you'll create a new Run configuration for the app.

Under the Run configurations dropdown, select Edit configurations... option.

Edit run configurations

Click on the + button in the peak-left corner and select Android app from the list. This will create a new empty Run configuration for Android app.

New run configuration details

Set the following properties for the new configuration:

  • Under Name, enter Deep link test.
  • Under Module, select app.
  • Nether Launch options select URL
  • Nether URL, enter bookmanstreasure://domicile/favorites.

Now, click on Apply and and then OK.

Select the new configuration from Run configurations dropdown and run it.

Select deep link run config

The app should open the Favorites screen.

App opened to Favorites

Nested graphs

To heighten readability and reusability, ane navigation graph tin be embedded into some other. Create a new navigation graph named book_nav_graph.xml - use the same steps you used as when creating nav_graph.xml.

Replace the auto-generated content for the navigation tag with this:

<navigation xmlns:android="http://schemas.android.com/apk/res/android"   xmlns:app="http://schemas.android.com/apk/res-auto"   xmlns:tools="http://schemas.android.com/tools"   android:id="@+id/bookDetailsGraph"   app:startDestination="@id/workDetailsFragment">  </navigation>        

There are ii things to notation:

  • workDetailsFragment is set as the showtime destination.
  • The ID of the nested graph has been fix to bookDetailsGraph.

Now, open up nav_graph.xml and move the post-obit actions and destinations to book_nav_graph:

  • actionShowAuthor
  • workDetailsFragment
  • bookDetailsFragment
  • authorDetails

In nav_graph.xml and add together the post-obit between the navigation tags:

<include app:graph="@navigation/book_nav_graph" />        

Now, open up BookSearchFragment and find:

findNavController().navigate(   R.id.actionBookDetails,   WorkDetailsViewModel.createArguments(it) )        

Replace it with:

findNavController().navigate(   R.id.bookDetailsGraph,   WorkDetailsViewModel.createArguments(it) )        

Note the ID change — y'all're now pointing to the nested graph. Exercise the same for FavoritesFragment, so build and run to make certain everything notwithstanding works!

Conditional Navigation

The final remaining task is to open the Favorites screen if any books have been favorited.

Open nav_graph.xml and add a new destination for LauncherFragment:

<fragment   android:id="@+id/launcherFragment"   android:name="com.raywenderlich.android.bookmanstreasure.ui.launcher.LauncherFragment"   android:label="Blank"   tools:layout="@layout/fragment_book_details">   <action     android:id="@+id/actionBookSearch"     app:destination="@id/bookSearchFragment" />   <activity     android:id="@+id/actionFavorites"     app:destination="@id/favoritesFragment" /> </fragment>        

The XML should feel familiar – it's a fragment destination with two actions.

Update the startDestination attribute of the navigation tag to be the following:

app:startDestination="@+id/launcherFragment"        

Adjacent, open the LauncherFragment and detect:

//TODO implement navigating to Search or Favorites        

Supplant it with the following:

val destination = if (it.hasFavorites()) {   R.id.actionFavorites } else {   R.id.actionBookSearch }  findNavController().navigate(     destination,     null,     NavOptions.Architect().setPopUpTo(         R.id.launcherFragment,         true     ).build() )        

Add together the post-obit imports:

import androidx.navigation.fragment.findNavController import androidx.navigation.NavOptions        

This will check if at that place are any favorites and show the appropriate screen. Note the third statement passed to the navigate() role. It specifies navigation options. In this case, it clears the backstack to prevent the user from navigating back to the LauncherFragment.

Notation: For a list of all the options available, check theNavOptions.Builder official documentation.

At present, build an run the app. Search for a book, tap on 1 of the results and add together a favorite by tapping on the ❤︎ icon on the top-correct.

Adding a favorite

Exit the app, and so launch it again. You should land on the Favorites screen.

Where to Go From Hither?

You can download the final project using the Download materials button at the top or bottom of the tutorial.

Now you know how to utilize the Navigation architecture component! Fifty-fifty though it is still in beta, it eases development quite a flake.

A peachy place to detect more information is the official documentation from Google. Also be sure to check out our screencast on the topic.

If you have whatever questions or tips for others on using the Navigation architecture component, delight join in on the forum discussion below!

Source: https://www.raywenderlich.com/6014-the-navigation-architecture-component-tutorial-getting-started

Posted by: wilsonsawran56.blogspot.com

0 Response to "How To Register Custum Class In Androidmanifest.xml"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel