What are Fragments?
Fragment represents a behavior or a portion of a user interface in a
FragmentActivity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. Fragments are to encapsulate state within your UI components and to create the layout that scale and adapt to accommodate a variety of device types, screen sizes, and resolutions.
Official Docs on Fragments.
What I will do in this article are:
- First, I will create snippet_view_contact_toolbar.xml :
2. Create snippet_search_toolbar.xml :
3. After creating the above two snippets we have to merge/combine those two XML files into a single fragment layout called fragment_viewcontacts.xml.
4. Now in activity_main.xml, we need to change the parent view group to CoordinatorLayout & inside this, add a FrameLayout which will have an id of fragment_container(android: id = ”@+id/fragment_container”).
Now the XML part is done. We have to work on the Java code.
5. Create ToolbarFragment.java file which will extend the Fragment class and need to include the fragment code and logic in it.
6. In the final part, we need to initialize the ToolbarFragment.java in MainActivity.java.
So that’s the above 6 steps where I mentioned briefly what I gonna do. So let's jump into writing the code:
Go to: res > values > style.xml and change this:
Before creating XML, create the icon from Drawable (right click) > new > Image Asset and select icon to the Action bar and Tab bar. Select the asset type to Clip Art. Create the back button and search icon separately. In case of back button choose a custom color to blue and for search icon choose white custom color as you can see in the gif above in the article.
Create snippet_search_toolbar.xml :
In Res > Drawable create grey_border_bottom.xml:
Change a few things to activity_main.xml:
Finally, We have made a Search Box in Action Bar using Fragments 👍🏼✌️🏻😇😇
Thanks For Reading this article. If you have any doubt, don’t hesitate to ask questions on the comment box.
THANKS, AND HAPPY CODING! 💻 📱