Why my toolbar doesn't hide when SearchView action appears? - android

This is my toolbar
I am trying to create a search toolbar with Search ActionView, but when I opening the search bar the title of my toolbar is not being hidden. I tried to add in the menu.xml showAsAction = "collapseActionView" but it remains the same.
Here is my code:
AndroidManifest.xml
<activity
android:name="com.apps.screens.ContactsActivity"
android:exported="true"
android:parentActivityName=".MainActivity"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar" />
Activity.java
public class ContactsActivity extends AppCompatActivity {
private List<Contact> items;
private RecyclerView recyclerView;
private ContactPhoneAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.contacts_menu, menu);
MenuItem item = menu.findItem(R.id.search);
SearchView searchView = (SearchView) item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
return true;
}
}
menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/search"
android:icon="#drawable/ic_search"
android:title="Search"
app:showAsAction="always"
app:actionViewClass="androidx.appcompat.widget.SearchView"/>
</menu>
layout.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".screens.ContactsActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay"
app:elevation="0dp">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:title="Select Contact"
android:background="#color/white" />
</com.google.android.material.appbar.AppBarLayout>
<include layout="#layout/content_contacts" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
I appreciate any suggestion

In this piece of code , add the following line of code
searchview.maxWidth = Integer.MAX_VALUE
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.contacts_menu, menu);
MenuItem item = menu.findItem(R.id.search);
SearchView searchView = (SearchView) item.getActionView();
searchview.maxWidth = Integer.MAX_VALUE // add this line of code
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
return true;
}
}

Related

SearchView widget text not aligned to left/start of Toolbar

I'm implementing SearchView in Activity. Everything works fine as expected but the text starts or is aligned to center rather than left.
Below is the xml code
search_toolbar.xml
<item
android:id="#+id/m_search"
android:icon="#drawable/ic_search"
android:title=""
android:visible="true"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom|collapseActionView" />
In main activity I have callbacks defined which I use in the fragments to refresh the data based on the query.
Main activity code
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.search_toolbar, menu);
MenuItem item = menu.findItem(R.id.m_search);
MenuItemCompat.setOnActionExpandListener(item, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Called when SearchView is collapsing
if (item.isActionViewExpanded()) {
animateSearchToolbar(1, false, false);
toolbar_title.setVisibility(View.VISIBLE);
}
return true;
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Called when SearchView is expanding
toolbar_title.setVisibility(View.GONE);
animateSearchToolbar(1, true, true);
return true;
}
});
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.m_search));
searchView.setGravity(Gravity.START);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Log.w(TAG, "onQueryTextSubmit : " + query);
if (!TextUtils.isEmpty(query)) {
callback.searchQuery(query);
}
hideKeyboard();
return true;
}
#Override
public boolean onQueryTextChange(String s) {
Log.w(TAG, "onQueryTextChange : " + s);
if (TextUtils.isEmpty(s)) {
hideKeyboard();
callback.refreshData();
}
return false;
}
});
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
Log.w(TAG, "OnCloseListener : ");
return false;
}
});
searchView.setOnSearchClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.w(TAG, "OnSearchClickListener : ");
}
});
return true;
}
This is main_activity.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/appBarLayout"
android:background="#android:color/white"
android:gravity="center">
<android.support.design.widget.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
app:layout_collapseMode="parallax"
app:popupTheme="#style/AppTheme.PopupOverlay">
<tlb.com.customviews.TextViewMedium
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="#string/title"
android:textAllCaps="true"
android:textColor="#color/button_color"
android:textSize="#dimen/text_size_18"/>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/bottomNavigationView"
android:background="#android:color/white"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottomNavigationView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#color/white"
app:itemBackground="#drawable/bottom_navigation_colors"
app:itemIconSize="#dimen/bottom_navigation_icon_size"
app:itemTextAppearance="#style/menu_text_style"
app:menu="#menu/bottom_navigation_menu" />
</RelativeLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigationView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/activity_main_drawer" />
Try changing
searchView.setGravity(Gravity.START);
for
searchView.setGravity(Gravity.LEFT);

Android toolbar : Why three dots does not appear ?

Why I create toolbar I do not have three dots who will appear. How can I do ?
public class Main extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
}
And XML :
<?xml version="1.0" encoding="utf-8"?>
<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="woowin.woowin.Main">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#393939"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
/>
</RelativeLayout>
And can you explain me, how add options in this three dots after that ?
thank you
you forgot to add your menu in your activity use below code to add menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.your_menu, menu);
return true;
}
You need to add at least one menu item either via XML or in java code using add into your menu to see the menu options
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0,0,0,"title");
return true;
}

Getting error searchView on null reference

I have searchView on actionbar and I here is codes for it
public class container extends AppCompatActivity {
private ListView drawerList;
private DrawerLayout drawerLayout;
private Toolbar toolbar;
private ActionBarDrawerToggle toggle;
private TextView textContainer, titleContainer;
private ImageView imageContainer;
private drawerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_container);
toolbar = (Toolbar) findViewById(R.id.mainToolbar);
setSupportActionBar(toolbar);
toolbar.setTitleTextColor(0xffffffff);
titleContainer = (TextView) findViewById(R.id.containerTitle);
textContainer = (TextView) findViewById(R.id.textContainer);
imageContainer = (ImageView) findViewById(R.id.imageContainer);
titleContainer.setText(R.string.UtrujjTitle);
textContainer.setText(R.string.UtrujjContent);
imageContainer.setImageResource(R.drawable.utrujj);
final Animation animation = AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
drawerLayout = (DrawerLayout) findViewById(R.id.mainDrawer);
drawerList = (ListView) findViewById(R.id.drawerList);
final SearchView searchView = (SearchView)findViewById(R.id.searchable);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if (newText.length() > 0) {
Spannable spannable = new SpannableString(newText);
spannable.setSpan(new BackgroundColorSpan(Color.YELLOW), 0, 100, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textContainer.setText(spannable);
}
return false;
}
});
and in the end I added these overrides
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search, menu);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.searchable:
return false;
default:
break;
}
return super.onOptionsItemSelected(item);
}
search.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/setting"
android:icon="#drawable/ic_setting"
app:showAsAction="ifRoom"
android:title="#string/setting"/>
<item android:id="#+id/searchable"
android:icon="#android:drawable/ic_menu_search"
app:showAsAction="always"
app:actionViewClass="android.support.v7.widget.SearchView"
android:title="#string/search"/>
</menu>
when activity start I get this error in logcat
Unable to start activity ComponentInfo{com.example.tina.tibbenabvi/com.example.tina.tibbenabvi.container}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SearchView.setOnQueryTextListener(android.widget.SearchView$OnQueryTextListener)' on a null object reference
====================================================
This view It's a menu item so you should initialize onCreateOptionsMenu().
Example:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if (newText.length() > 0) {
Spannable spannable = new SpannableString(newText);
spannable.setSpan(new BackgroundColorSpan(Color.YELLOW), 0, 100, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textContainer.setText(spannable);
}
return false;
}
});
return true;
}
EDIT
Manifest file:
<activity ... >
...
<meta-data android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
Create res/xml/searchable.xml file:
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="#string/app_name"
android:hint="search..." />
Create a Searchable Activity
public class SearchResultsActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
...
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
...
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
//use the query to search your data somehow
}
}
...
}
And add it in the manifest file:
<activity android:name=".SearchResultsActivity" ... >
...
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
...
</activity>
Info from:
http://developer.android.com/intl/es/training/search/setup.html

Why setOnQueryTextListener() gets "on a null object reference" error?

I'm trying to add search icon to toolbar which pressed would open search bar.
But every method I tried didn't work and no icon appears.
Now I get this error and just can't find solution to it:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.SearchView.setOnQueryTextListener(android.support.v7.widget.SearchView$OnQueryTextListener)' on a null object reference
at pl.michalz.hideonscrollexample.activity.partthree.PartThreeActivity.onCreateOptionsMenu(PartThreeActivity.java:62)
This is my main Activity:
public class PartThreeActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.AppThemeBlue);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_part_three);
initToolbar();
initViewPagerAndTabs();
}
#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);
MenuItem seachItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView)
MenuItemCompat.getActionView(seachItem);
searchView.setOnQueryTextListener(
new SearchView.OnQueryTextListener(){
#Override
public boolean onQueryTextSubmit(String query) {
Log.d("myApp", "onQueryTextSubmit ");
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
Log.d("myApp", "onQueryTextChange ");
return false;
}
});
return true;
}
private void initToolbar() {
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
setTitle(getString(R.string.app_name));
mToolbar.setTitleTextColor(getResources().getColor(android.R.color.white));
}
private void initViewPagerAndTabs() {
ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
pagerAdapter.addFragment(PartThreeFragment.createInstance(), getString(R.string.tab_1));
pagerAdapter.addFragment(BlankFragment.createInstance("F word"), getString(R.string.tab_2));
viewPager.setAdapter(pagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
}
static class PagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
public PagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
public void addFragment(Fragment fragment, String title) {
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
}
//kai paskaudzia toolbaro iconas
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
// User chose the "Settings" item, show the app settings UI...
return true;
case R.id.action_search:
// User chose the "Favorite" action, mark the current item
// as a favorite...
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
}
main Activity.xml
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways|snap" />
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="#android:color/white"
app:tabIndicatorHeight="6dp"
app:tabSelectedTextColor="#android:color/white"
app:tabTextColor="#android:color/white" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
Also searchable.xml
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:hint="#string/hint"
android:label="#string/app_name" />
And res/menu/menu_main.xml, added ic_search myself to drawable
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/tools">
<item
android:id="#+id/action_search"
android:icon="#drawable/ic_search"
android:title="#string/action_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom|collapseActionView" />
<!-- Settings, should always be in the overflow -->
<item
android:id="#+id/action_settings"
android:title="#string/action_settings"
app:showAsAction="never" />
</menu>
Could someone help?
I fixed error by changing namespace in menu_main.xml from app to my own myapp and it fixed automaticly by pressing "Alt+Enter".
res/menu/menu_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/tools"
//----------- it created automaticly --------------
xmlns:myapp="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_search"
android:icon="#drawable/ic_search"
android:title="#string/action_search"
//-------------- H E R E --------------------
myapp:showAsAction="always|collapseActionView"
myapp:actionViewClass="android.support.v7.widget.SearchView" />
<!-- Settings, should always be in the overflow -->
<item
android:id="#+id/action_settings"
android:title="#string/action_settings"
app:showAsAction="never" />
</menu>
Main Activity
#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);
Log.w("myApp", "onCreateOptionsMenu -started- ");
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
MenuItem menuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
searchView.setSearchableInfo( searchManager.getSearchableInfo(getComponentName()));
searchView.setQueryHint(getResources().getString(R.string.hint));
searchView.setOnQueryTextListener(
new SearchView.OnQueryTextListener(){
#Override
public boolean onQueryTextSubmit(String query) {
Log.w("myApp", "onQueryTextSubmit ");
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
Log.w("myApp", "onQueryTextChange ");
return false;
}
});
return true;
}
I faced the same problem. Solution is Simple.
Always check imports when doing alt+enter.
I did alt+enter and android.widget.SearchView got imported, whereas my implementation expected android.support.v7.widget.SearchView

How to use SearchView in Toolbar Android

The code on which I am working, is using a Toolbar and inflating a menu.
Here is the code
private Toolbar mToolbar;
mToolbar.inflateMenu(R.menu.chat_screen_menu);
setupMenu ();
private void setupMenu ()
{
mMenu = mToolbar.getMenu();
if (mMenu != null)
{
if (mChatPager != null && mChatPager.getCurrentItem() > 0)
{
mMenu.setGroupVisible(R.id.menu_group_chats, true);
mMenu.setGroupVisible(R.id.menu_group_contacts, false);
}
else
{
mMenu.setGroupVisible(R.id.menu_group_chats, false);
mMenu.setGroupVisible(R.id.menu_group_contacts, true);
mMenu.setGroupVisible(R.id.menu_group_otr_verified,false);
mMenu.setGroupVisible(R.id.menu_group_otr_unverified,false);
mMenu.setGroupVisible(R.id.menu_group_otr_off,false);
}
}
mToolbar.setOnMenuItemClickListener(new OnMenuItemClickListener ()
{
..........
}
}
But now, they require a Search button in the tool_bar.
I managed to put it, I followed a guide here
When I try to write something to search, the toast I had put to test the listener never shown.
which indicates listener is not working
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.chat_screen_menu, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
mSearchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_menu_search));
final Toast toast = new Toast(mApp);
if (mSearchView != null )
{
mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
mSearchView.setIconifiedByDefault(false);
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener()
{
public boolean onQueryTextChange(String newText)
{
mSearchString = newText;
//doFilterAsync(mSearchString);
toast.makeText(getApplicationContext(), "Test1", Toast.LENGTH_LONG).show();
return true;
}
public boolean onQueryTextSubmit(String query)
{
mSearchString = query;
//doFilterAsync(mSearchString);
toast.makeText(getApplicationContext(), "Test2", Toast.LENGTH_LONG).show();
return true;
}
};
mSearchView.setOnQueryTextListener(queryTextListener);
}
return true;
}
You have to use Appcompat library for that. Which is used like below:
dashboard.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_search"
android:icon="#android:drawable/ic_menu_search"
app:showAsAction="always|collapseActionView"
app:actionViewClass="androidx.appcompat.widget.SearchView"
android:title="Search"/>
</menu>
Activity file (in Java):
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.dashboard, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) MainActivity.this.getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = null;
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName()));
}
return super.onCreateOptionsMenu(menu);
}
Activity file (in Kotlin):
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_search, menu)
val searchItem: MenuItem? = menu?.findItem(R.id.action_search)
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
val searchView: SearchView? = searchItem?.actionView as SearchView
searchView?.setSearchableInfo(searchManager.getSearchableInfo(componentName))
return super.onCreateOptionsMenu(menu)
}
manifest file:
<meta-data
android:name="android.app.default_searchable"
android:value="com.apkgetter.SearchResultsActivity" />
<activity
android:name="com.apkgetter.SearchResultsActivity"
android:label="#string/app_name"
android:launchMode="singleTop" >
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
searchable xml file:
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:hint="#string/search_hint"
android:label="#string/app_name" />
And at last, your SearchResultsActivity class code. for showing result of your search.
If you would like to setup the search facility inside your Fragment, just add these few lines:
Step 1 - Add the search field to you toolbar:
<item
android:id="#+id/action_search"
android:icon="#android:drawable/ic_menu_search"
app:showAsAction="always|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"
android:title="Search"/>
Step 2 - Add the logic to your onCreateOptionsMenu()
import android.support.v7.widget.SearchView; // not the default !
#Override
public boolean onCreateOptionsMenu( Menu menu) {
getMenuInflater().inflate( R.menu.main, menu);
MenuItem myActionMenuItem = menu.findItem( R.id.action_search);
searchView = (SearchView) myActionMenuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// Toast like print
UserFeedback.show( "SearchOnQueryTextSubmit: " + query);
if( ! searchView.isIconified()) {
searchView.setIconified(true);
}
myActionMenuItem.collapseActionView();
return false;
}
#Override
public boolean onQueryTextChange(String s) {
// UserFeedback.show( "SearchOnQueryTextChanged: " + s);
return false;
}
});
return true;
}
If you want to add it directly in the toolbar.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<SearchView
android:id="#+id/searchView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:iconifiedByDefault="false"
android:queryHint="Search"
android:layout_centerHorizontal="true" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
Integrating SearchView with RecyclerView
1) Add SearchView Item in Menu
SearchView can be added as actionView in menu using
app:useActionClass = "android.support.v7.widget.SearchView"
.
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="rohksin.com.searchviewdemo.MainActivity">
<item
android:id="#+id/searchBar"
app:showAsAction="always"
app:actionViewClass="android.support.v7.widget.SearchView"
/>
</menu>
2) Implement SearchView.OnQueryTextListener in your Activity
SearchView.OnQueryTextListener has two abstract methods. So your activity skeleton would now look like this after implementing SearchView text listener.
YourActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{
public boolean onQueryTextSubmit(String query)
public boolean onQueryTextChange(String newText)
}
3) Set up SerchView Hint text, listener etc
#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);
MenuItem searchItem = menu.findItem(R.id.searchBar);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setQueryHint("Search People");
searchView.setOnQueryTextListener(this);
searchView.setIconified(false);
return true;
}
4) Implement SearchView.OnQueryTextListener
This is how you can implement abstract methods of the listener.
#Override
public boolean onQueryTextSubmit(String query) {
// This method can be used when a query is submitted eg. creating search history using SQLite DB
Toast.makeText(this, "Query Inserted", Toast.LENGTH_SHORT).show();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.filter(newText);
return true;
}
5) Write a filter method in your RecyclerView Adapter.
You can come up with your own logic based on your requirement. Here is the sample code snippet to show the list of Name which contains the text typed in the SearchView.
public void filter(String queryText)
{
list.clear();
if(queryText.isEmpty())
{
list.addAll(copyList);
}
else
{
for(String name: copyList)
{
if(name.toLowerCase().contains(queryText.toLowerCase()))
{
list.add(name);
}
}
}
notifyDataSetChanged();
}
Full working code sample can be found > HERE
You can also check out the code on SearchView with an SQLite database in this Music App
Implementing the SearchView without the use of the menu.xml file and open through button
In your Activity we need to use the method of the onCreateOptionsMenumethod in which we will programmatically inflate the SearchView
private MenuItem searchMenu;
private String mSearchString="";
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
SearchManager searchManager = (SearchManager) StoreActivity.this.getSystemService(Context.SEARCH_SERVICE);
SearchView mSearchView = new SearchView(getSupportActionBar().getThemedContext());
mSearchView.setQueryHint(getString(R.string.prompt_search)); /// YOUR HINT MESSAGE
mSearchView.setMaxWidth(Integer.MAX_VALUE);
searchMenu = menu.add("searchMenu").setVisible(false).setActionView(mSearchView);
searchMenu.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
assert searchManager != null;
mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
mSearchView.setIconifiedByDefault(false);
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
public boolean onQueryTextChange(String newText) {
mSearchString = newText;
return true;
}
public boolean onQueryTextSubmit(String query) {
mSearchString = query;
searchMenu.collapseActionView();
return true;
}
};
mSearchView.setOnQueryTextListener(queryTextListener);
return true;
}
And in your Activity class, you can open the SearchView on any button click on toolbar like below
YOUR_BUTTON.setOnClickListener(view -> {
searchMenu.expandActionView();
});
I search and implement so much code but that not worked for me .
Then I implement custom toolbar into my XML file and then inside toolbar tag I use searchview tag.
Hope it work for you.

Categories

Resources