Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Styling the ActionBar with Search field in Material Theme

    • 0
    • 2
    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 1.06k
    Comment on it

    In this blog we use Toolbar, it is more generalization form of ActionBar. It support more feature than ActionBar.
    Toolbar is added in API level 21 but the good thing is we can use it in the below version by using supporting library.
    First you to select the Theme.AppCompat.NoActionBar in styles.xml :-

    <!-- Base application theme. -->
        <style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
            <!-- Customize your theme here. -->
        </style>
    

    Create a xml file with name toolbar.xml

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v7.widget.Toolbar
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:elevation="4dp"
        android:id="@+id/toolbar"
        android:background="#4082EE">
    
    </android.support.v7.widget.Toolbar>
    

    Create a xml file with name search_bar.xml in which we add EditText for search

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">
    
        <EditText
            android:id="@+id/edtSearch"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:imeOptions="actionSearch"
            android:inputType="text" />
    
    </LinearLayout>
    

    Now in the main layout (activity_main.xml) include toolbar.xml

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
    
        tools:context=".MainActivity">
    
        <include
            android:id="@+id/toolbar"
            layout="@layout/toolbar"></include>
    
    </RelativeLayout>
    

    create menu_main.xml file inside menu folder

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />
    
    <item
        android:id="@+id/action_search"
        android:title="Search"
        android:orderInCategory="200"
        android:icon="@drawable/ic_menu_search"
        app:showAsAction="ifRoom"
        />
    

    Now create your Activity like this:-

    **
     * Activity that contains a custom Action bar with Material Design and search field
     */
    public class MainActivity extends AppCompatActivity {
    
    
        private Toolbar toolbar;
        private MenuItem menuItem;
        private boolean isSearchOpened = false;
        private EditText searchEditText;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
        }
    
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
    
    
    
            switch (id) {
                case R.id.action_settings:
                    return true;
                case R.id.action_search:
                    handleMenuSearch();
                    return true;
            }
    
            return super.onOptionsItemSelected(item);
        }
    
        @Override
        public boolean onPrepareOptionsMenu(Menu menu) {
            menuItem = menu.findItem(R.id.action_search);
            return super.onPrepareOptionsMenu(menu);
        }
    
        /**
         * methods hides the keyboard
         *
         * @param view
         */
        private void hideKeyboard(View view) {
            //hides the keyboard
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    
        /**
         * methods show the keyboard
         *
         * @param view
         */
        private void showKeyboard(View view) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
        }
    
        /**
         * method handles the search logic
         */
        private void handleMenuSearch() {
            ActionBar action = getSupportActionBar(); //get the actionbar
    
            if (isSearchOpened) { //test if the search is open
    
                action.setDisplayShowCustomEnabled(false); //disable a custom view inside the actionbar
                action.setDisplayShowTitleEnabled(true); //show the title in the action bar
    
                hideKeyboard(searchEditText);
    
    
                //add the search icon in the action bar
                menuItem.setIcon(getResources().getDrawable(android.R.drawable.ic_menu_search));
    
                isSearchOpened = false;
            } else { //open the search entry
    
                action.setDisplayShowCustomEnabled(true); //enable it to display a
                // custom view in the action bar.
                action.setCustomView(R.layout.search_bar);//add the custom view
                action.setDisplayShowTitleEnabled(false); //hide the title
    
                searchEditText = (EditText) action.getCustomView().findViewById(R.id.edtSearch); //the text editor
    
                //this is a listener to do a search when the user clicks on search button
                searchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                            doSearch();
                            return true;    
                        }
                        return false;
                    }
                });
    
                searchEditText.requestFocus();
    
                //open the keyboard focused in the edtSearch
                showKeyboard(searchEditText);
    
                //add the close icon
                menuItem.setIcon(getResources().getDrawable(android.R.drawable.ic_menu_delete));
    
                isSearchOpened = true;
            }
        }
    
        @Override
        public void onBackPressed() {
            if(isSearchOpened) {
                handleMenuSearch();
                return;
            }
            super.onBackPressed();
        }
    
        private void doSearch() {
    //
        }
    }
    

 1 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: