How to make a Search Box in Action Bar using Fragments In Android

Animesh Roy
Apr 27 · 3 min read
In this article, I will show you how you can achieve this using Fragment

What are Fragments?

A 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:

  1. 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 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 in

So that’s the above 6 steps where I mentioned briefly what I gonna do. So let's jump into writing the code:

Step 1:

Go to: res > values > style.xml and change this:

Create snippet_view_contact_toolbar.xml:

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.

Step 2:

Create snippet_search_toolbar.xml :

In Res > Drawable create grey_border_bottom.xml:

Step 3:

Create fragment_viewcontacts.xml:

Step 4:

Change a few things to activity_main.xml:

Step 5:


Step 6:


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.


Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade