How can I dismiss/close a searchview after a Query Text is submitted?

FedericoNavarreteFedericoNavarrete SVMember ✭✭
edited December 2016 in Xamarin.Android

This is my current code:

private async void _searchView_QueryTextSubmit(object sender, SearchView.QueryTextSubmitEventArgs e)
{
if (!string.IsNullOrEmpty(e.Query))
{
if (allDishes.Count > 0)
{
Intent objIntent = new Intent(this, typeof(SearchResult));
objIntent.PutExtra("query", e.Query);
StartActivity(objIntent);
_searchView.ClearFocus();
_searchView.SetQuery("", false);
_searchView.SetIconifiedByDefault(true);
_searchView.OnActionViewCollapsed();
}
else
{
Toast.MakeText(this, GetString(Resource.String.lblNoData), ToastLength.Short).Show();
}
}
}

But when I press back from the other activity the SearchView is always open:

Do anyone know what should I change?

Thanks for your help.

Posts

  • I was able to do a little trick:

    I created a variable for checking the current status of the SearchView:

    private bool? submittedQuery = null;

    Later, on the OnWindowFocusChanged I press the BackButton and it closes it and works as expected.

        public override void OnWindowFocusChanged(bool hasFocus)
        {
            if (submittedQuery != null)
            {
                _searchView.OnActionViewCollapsed();
                _searchView.ClearFocus();
                base.OnBackPressed();
                submittedQuery = null;
            }
        }
    
        public override bool OnOptionsItemSelected(IMenuItem item)
        {
            switch (item.ItemId)
            {
                case Resource.Id.action_search:
                    submittedQuery = false;
                    return true;
                default:
                    return false;
            }
        }
    
        private void _searchView_QueryTextSubmit(object sender, SearchView.QueryTextSubmitEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.Query))
            {
                submittedQuery = true;
            }
        }
    
    #pragma warning disable CS0618 // Type or member is obsolete
    private class ExpandListener : Java.Lang.Object, MenuItemCompat.IOnActionExpandListener
    #pragma warning restore CS0618 // Type or member is obsolete
    {
        MainActivity mAct;
    
        public ExpandListener(MainActivity mActivity)
        {
            mAct = mActivity;
        }
        public bool OnMenuItemActionCollapse(IMenuItem item)
        {
            mAct.submittedQuery = null;
            return true;
        }
    
        public bool OnMenuItemActionExpand(IMenuItem item)
        {
            //Stuff
            return true;
        }
    }
    
Sign In or Register to comment.