Hi guys. When I open Activity 2 from Fragment 1 with intent and press back on Activity 2, my keyboard would pop up automatically if setIconifiedByDefault is false when I create the searchView in actionBar in Fragment 1. I tried to remove searchView.setIconifiedByDefault(false);
. Everything works perfect (nothing pop up when I press back in Activity 2) but I cannot get the exact layout I want. Any suggestions to avoid the keyboard pop up?
In Fragment 1, I have below code to create searchView in actionBar
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the options menu from XML
inflater.inflate(R.menu.homesearchbar, menu);
super.onCreateOptionsMenu(menu,inflater);
SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setMaxWidth(Integer.MAX_VALUE);
searchView.setIconifiedByDefault(false);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) { return false; }
@Override
public boolean onQueryTextChange(String newText) { return false; }
});
}
Edit - homesearchbar
<?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:title=""
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always"/>
</menu>
If you want to keep your keyboard state hidden then you should enter this in your onResume()
method: And this is happening because your textfield always takes the focus whenever you start or resume your activity/fragment. To stop that one way is the following:
@Override
public void onResume() {
super.onResume();
InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(yourTextField.getWindowToken(), 0);
}
Or if you can't get your searchfield in onResume then use this instead:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
And another way is to declare "stateHidden"
attribute in activity tag
in your manifest.
You can also set setFocusable(false)
for searchView
and setFocusable(true)
in your fragment 1. So that it won't take the focus. and all credits to you for this.