Join Albert Lo for an in-depth discussion in this video Implement model: NavBarItem, part of Android Development: Modern Android UI Design Elements.
- [Instructor] We have created TextViews for our navigation drawer items. These TextViews will have view IDs associated with it. So the plan is to create a new model in the form of an enum to hold the view IDs of the TextViews. First, let's get rid of the navigation view, because it's not a part of the project. And we go into project, under app, under Java, under the package name. Let's create a new package.
We'll call it models. And under the models package, let's create a new Java class. We will call it NavBarItem, and it will be of type enum. The reason that we are creating an enum is so that we will not have to worry about the ordering of the on click handlers of those TextViews in any certain sequence. For our enum, the first item will be Google_photos.
For the enum constructor, we will pass in the view ID for Google_photos. We will select the package name for the resource, and select Google_photos. The next one will be Twitter, and we will use the resource name for Twitter. The next NavBarItem we will add is Facebook. Now, if you have not built your app yet, now is a good time to do so, so that all your resources will show up in the autocomplete.
We select the Facebook resource, the last one we will define as our NavBarItem is settings. And I will select the resource for settings. Now, in our enum, we are going to define our constructor. Our constructor will take in one parameter, which is the item ID. Let's define our item ID up here, it will be a private type integer, item ID.
In our constructor, we are going to initialize our item ID. The next thing we will do is add a public method, called getItemId, and it will just return our private class member. The last method that we will add to our NavBarItem enum will be a static method.
This static method will take a view ID and map it to a NavBarItem, so our method is called fromViewId, it's a public static method, it returns a NavBarItem, and the name again is fromViewId. And the input parameter for fromViewId method is a viewId. To return a NavBarItem from a viewId, we will insert a for loop.
This for loop will iterate through all of our NavBarItems, and for each enum in the iteration, it will make a comparison. It's going to check whether the getItemId is equal to the passed in viewId. And if it is, we just simply return our NavBarItem.
If we have not been able to find our NavBarItem from the passed in viewId, we are going to declare an error, and we'll pass in a string, cannot find viewType.
- Creating a custom layout with XML
- Setting up OnClick handlers
- Making API calls
- Creating custom views
- Implementing ViewHolder objects
- Signing certificates
- Adding a checkbox