How to auto collapse ActionBar SearchView on Soft Keyboard close in Android

In this android programming source code example, we are going to explore how to auto collapse actionbar searchview on soft keyboard close in android.

Below is a step by step source code to auto collapse actionbar searchview on soft keyboard close in android.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusable="true"
    android:focusableInTouchMode="true">

</RelativeLayout>

MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;

import com.bluapp.androidview.R;

public class SearchViewActivity8 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_view8);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        MenuInflater inflater = getMenuInflater();inflater.inflate(R.menu.searchview_option8, menu);
        return super.onCreateOptionsMenu(menu);
    }

}

menu/searchview_option8.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/menu_searchview"
        android:title="@string/searchname"
        android:iconifiedByDefault="true"
        android:icon="@android:drawable/ic_menu_search"
        app:actionViewClass="android.support.v7.widget.SearchView"
        app:showAsAction="ifRoom|collapseActionView"/>

</menu>

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment