I am trying to display a search view as soon as I open my app and give it focus, and prevent the back arrow <-
, because pressing back causes :
I only wanted max 2 back actions to exit the activity. So I did the following in my search fragment:
public override void OnCreateOptionsMenu(IMenu menu, MenuInflater inflater) {
inflater.Inflate(Resource.Menu.search, menu);
var searchMenu = menu.FindItem(Resource.Id.action_search);
searchMenu.ExpandActionView();
_searchView = searchMenu.ActionView.JavaCast<SearchView>();
_searchView.SetIconifiedByDefault(false); // <-- I added this
_searchView.RequestFocus();
_searchView.QueryTextChange += async (s, e) => {
await PerformSearch(e.NewText);
};
var searchText = _searchView.FindViewById<TextView>(Resource.Id.search_src_text);
searchText.TextAlignment = TextAlignment.Center;
searchText.Hint = Resources.GetString(Resource.String.search_hint);
base.OnCreateOptionsMenu(menu, inflater);
}
menu:
<?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/action_search"
android:icon="@drawable/ic_search"
android:text="Search"
app:showAsAction="always" <-- I took out collapseActionView from here
app:actionViewClass="android.support.v7.widget.SearchView" />
</menu>
Now as soon as my activity launches and switches to the fragment I get this blank space on the left, how can I get rid of it?
This is the defaul blank space in Android OptionsMenu, you can not modify it. If your OptionsMenu only contain a SearchView item, there is a method to reduce its length. You could not use OptionsMenu, and add SearchView into Toolbar directly. You know OptionsMenu also is created based on Toolbar.
Therefore, you could find the xml code of Toolbar and add SearchView
as follows:
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" >
<android.support.v7.widget.SearchView
android:id="@+id/searchView"
android:text="Search"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v7.widget.Toolbar>
In Activiy, also add focus function code:
Android.Support.V7.Widget.SearchView searchView = FindViewById<Android.Support.V7.Widget.SearchView>(Resource.Id.searchView);
searchView.SetIconifiedByDefault(false);
searchView.RequestFocus();
searchView.QueryTextChange += (s, e) =>
{
//await PerformSearch(e.NewText);
Console.WriteLine(e.NewText);
};
var searchText = searchView.FindViewById<TextView>(Resource.Id.search_src_text);
searchText.TextAlignment = TextAlignment.Center;
searchText.Hint = Resources.GetString(Resource.String.search_hint);
The effect: