VasFou
VasFou

Reputation: 1669

How to hide soft input Keyboard when the Navigation drawer is being toggled , using fragments

So i have A navigation Drawer in the MainActivity and when a child of the expandable List View is being clicked the content is presented in a fragment. Inside the fragment i have a Menu icon , when clicked a search textbox is being displayed and the soft input Keyboard. but if someone push the toggle button to open the navigation drawer the soft input keyboard doesn't disappear. I have tried this methods :

First method: closing keyboard from MainActivity from onDrawerClosed ,using this code, nothing happened :

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

Second method : closing the Keyboard from MainActivity from the method onOptionsItemSelected(MenuItem item) , getting the item id and writing the same code as previous in the case : android.R.id.home, nothing happened

Third method : As the previous method but within the Fragment writing the above code, nothing happened :

  InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Service.INPUT_METHOD_SERVICE);
  imm.hideSoftInputFromWindow(ed_search.getWindowToken(), 0);

The soft Input Keyboard opens from the Fragment so i can't use something like the code in the above line because the ed_search is declared in the Fragment.

This is the code from the Main Activity:

public class MainActivity extends AppCompatActivity {

private static DrawerLayout mDrawerLayout;
private static ExpandableListView mExpandableListView;
private ActionBarDrawerToggle mActionBarDrawerToggle;
private Toolbar mToolbar;

//nav drawer Title
private CharSequence mDrawerTitle;

//used to store app titles
private String mTitles;

//slide menu items
private String[] navMenuItems;
private String[] navSubMenuItems;
private TypedArray  navMenuIcons;
private String[] navMenuLinks;

private List<NavDrawerItem> groupList;
private List<NavDrawerItem> childList;
private Map<NavDrawerItem, List<NavDrawerItem>> mapList;
private ExpandableListViewAdapter mAdapter;
//Fragment
private FragmentManager lFragmentManager;
private Fragment lFragment;
private static final NavDrawerItem firstItem = new NavDrawerItem("Latest",
        "http://thegadgetflow.com/?feed=full_feed&amp;paged=%d");

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    /**
     * Toolbar customization
     */
    mToolbar = (Toolbar)findViewById(R.id.toolbar);
    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    mTitles = firstItem.getTitle(); //setting the title of the first item
    getSupportActionBar().setTitle("  Home");// changing the title of the action bar with the name of the item
    /**
     * Home screen
     */
    lFragmentManager = getFragmentManager();
    lFragment = lFragmentManager.findFragmentById(R.id.frame_container);
    lFragment = new FragmentListItemHome();
    Bundle mBundle = new Bundle();
    mBundle.putSerializable("Item", firstItem);
    lFragment.setArguments(mBundle);
    //To the fragment
    lFragmentManager.beginTransaction().replace(R.id.frame_container ,lFragment ).commit();
    //navigation Drawer
    mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
    //populate the expandable List view
    createGroupList();
    CreateChildList();
    //put a reference to the expandable List view
    mExpandableListView = (ExpandableListView)findViewById(R.id.list_slideMenu);
    /**
     * changing the groupIndicator from left to right
     */
    mExpandableListView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
        @Override
        public void onLayoutChange(View v, int left, int top, int right, int bottom,
                                   int oldLeft, int oldTop, int oldRight, int oldBottom) {
            mExpandableListView.removeOnLayoutChangeListener(this);
            //getting the width of the Expandable List view
            int width = mExpandableListView.getWidth();

            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
                mExpandableListView.setIndicatorBounds(width - getDipsFromPixel(35), width
                        - getDipsFromPixel(5));
            } else {
                mExpandableListView.setIndicatorBoundsRelative(width - getDipsFromPixel(35), width
                        - getDipsFromPixel(5));
            }
        }
    });
    // A new adapter
    mAdapter = new ExpandableListViewAdapter(this, mapList, groupList);
    //setting the adapter
    mExpandableListView.setAdapter(mAdapter);
    /**
     * when a child of the Expandable list view is clicked
     */
    mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
        @Override
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
            final NavDrawerItem lItem = (NavDrawerItem) mAdapter.getChild(
                    groupPosition, childPosition);
            mTitles = lItem.getTitle();
            /**
             * A new fragment
             */
            boolean close = openListFragment(lItem);

            //closing the navigation drawer
            if (close) {
                mDrawerLayout.closeDrawer(mExpandableListView);
                //changing the title of the action bar with the title of the ChildItem
                mToolbar.setTitle("  " + lItem.getTitle());
            }
            return true;
        }
    });
    /**
     * toggling the sliding menu
     */

    mActionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar,
            R.string.app_name,   R.string.app_name) {

        @Override
        public void onDrawerClosed(View drawerView) {
            mToolbar.setTitle("  " + mTitles);
            invalidateOptionsMenu();

        }

        @Override
        public void onDrawerOpened(View drawerView) {
            mToolbar.setTitle("  Sidebar");
            invalidateOptionsMenu();
        }
    };
    mActionBarDrawerToggle.setHomeAsUpIndicator(R.drawable.ic_drawer);
    mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
    //changing the ScrimColor
    mDrawerLayout.setScrimColor(getResources().getColor(R.color.ColorPrimary));
    CommonUtils.setContext(getApplicationContext());
}
/***
 * Called when invalidateOptionsMenu() is triggered
 */
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    // if nav drawer is opened, hide the action items
    boolean drawerOpen = mDrawerLayout.isDrawerOpen(mExpandableListView);
    //hiding the menu items of the action bar if the navigation drawer is open
    if(mDrawerLayout!=null && drawerOpen)
        menu.clear();

    return super.onPrepareOptionsMenu(menu);
}
@Override
public void setTitle(CharSequence title) {
    mTitles = (String)title;
    mToolbar.setTitle("  Latest");
}
/**
 * When using the ActionBarDrawerToggle, you must call it during
 * onPostCreate() and onConfigurSationChanged()...
 */
@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    // Sync the toggle state after onRestoreInstanceState has occurred.
    mActionBarDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Pass any configuration change to the drawer toggles
    mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}

@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);
    menu.findItem(R.id.action_search).setVisible(false);
    menu.findItem(R.id.action_share).setVisible(false);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    // toggle nav drawer on selecting action bar app icon/title
    if (mActionBarDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }
    //not working
    switch (item.getItemId()){
        case android.R.id.home:
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            return true;
        default:
            return super.onOptionsItemSelected(item);

    }
}
/**
 * changing the title inside a fragment
 * @param title
 */
public void setActionBarTitle(String title) {
    mToolbar.setTitle(title);
}

@Override
protected void onResume()
{
    CommonUtils.resetBackButton();
    super.onResume();
}

And this is the code from the Fragment :

public class FragmentListItemHome extends Fragment {
RelativeLayout rl_row_progress_bar;
LinearLayout ln_search;
EditText ed_search;
private RecyclerView mRecyclerView;
private ArrayList<GadgetItem> mList;
private AdapterListItemHome mAdapter;
private GridLayoutManager mLayoutManager;
private String mUrl;
private String mTitleGadget;
private View v;
private ImageButton mImageButton;
int loadedPage;
NavDrawerItem mData;
String searchText;
boolean isSearchMode;
int maxScrolledPage = 0;
boolean preloadingCancelled;
int spanSize = 2;
int pauseCounter = 0;
InputMethodManager inputMethod;


//paging
Map<Integer, Boolean> _loadingPages = new HashMap<Integer, Boolean>();
Map<Integer, Integer> _pageIndexes = new HashMap<Integer, Integer>();
private Toolbar mToolbar;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    loadedPage = 1;
    /**
     * Toolbar customization
     */

    savedInstanceState = getArguments();
    if (savedInstanceState != null) {
        mData = (NavDrawerItem) savedInstanceState.getSerializable("Item");
    }
    isSearchMode = false;
    //for the search button in the action bar
    setHasOptionsMenu(true);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent , Bundle savedInstanceState) {
    if(parent == null)
        return null;
    if(v != null)
        return v;
    //initialize the view v
    v = inflater.inflate(R.layout.fragment_list_item_home, parent , false);
    //initialization Recycler view
   v.findViewById(R.id.rl_row_progress_bar_home); //the progress bar
    //search items
    mImageButton =(ImageButton)v.findViewById(R.id.anchor_home); //anchor
    ln_search = (LinearLayout) v.findViewById(R.id.ln_search_home); // the layout for searching
    ed_search = (EditText) v.findViewById(R.id.ed_search_home); // the text box for searching
    ed_search.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
    /**
     * Overriding the soft keyboard for the search text box
     */
    ed_search.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int Keycode, KeyEvent event) {
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (Keycode == KeyEvent.KEYCODE_SEARCH) || (Keycode == KeyEvent.KEYCODE_ENTER)) {
                inputMethod = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethod.hideSoftInputFromWindow(ed_search.getWindowToken(), 0);
                String key = ed_search.getText().toString();
                if (key != null && !key.isEmpty()) {
                    searchData(key);
                }
            }
            return false;
        }
    });
    /**
     * Scrolling
     */
    mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
        //getting the last visible position of the list
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            //when scrolling hide keyboard and search box
            ln_search.setVisibility(View.GONE);
            showKeyboard(false);

            int firstVisibleItems = mLayoutManager.findFirstVisibleItemPosition();

            if (newState == recyclerView.SCROLL_STATE_IDLE) {
                //Log.d("bill",String.valueOf(lastPosition));
                int onScrollingPage = getOnScrollingPage(firstVisibleItems);

                if (maxScrolledPage <= onScrollingPage)
                    maxScrolledPage = onScrollingPage;
                //int myPosition = layoutManager.getPosition();
                //hiding the anchor when the lastPosition is 0
                if (firstVisibleItems == 0)
                    mImageButton.setVisibility(View.GONE);

                loadPage(onScrollingPage + 1);
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            int firstVisibleItems = mLayoutManager.findFirstVisibleItemPosition();
            if (mLayoutManager != null && mLayoutManager.getItemCount() < 5) {
                return;
            } else {
                changeFooterState(true);
            }
            int visibleItemCount = mLayoutManager.getChildCount();
            int totalItemCount = mLayoutManager.getItemCount();
            int pastVisiblesItems = firstVisibleItems;
            // Log.d("bill","visibleItemCount: "+String.valueOf(visibleItemCount)+
            // "totalItemCount: "+String.valueOf(totalItemCount)+"firstVisibleItem: "+String.valueOf(pastVisiblesItems));
            if (pastVisiblesItems + visibleItemCount == totalItemCount && (mList != null && totalItemCount == mList.size())
                    && totalItemCount != 0) {
                changeFooterState(false);
            } else {
                changeFooterState(true);
            }
        }
    });
  }
/**
 * searching
 */
public void searchData(String searchKey) {
    loadedPage = 1;
    _loadingPages.clear(); // clear the hash map
    _pageIndexes.clear();
    isSearchMode = true;
    this.searchText = searchKey;

    if(mList != null && mAdapter != null) {
        mList.clear(); // clear the list
        mAdapter.notifyDataSetChanged();
    }

    // Set title bar
    ((MainActivity) getActivity())
            .setActionBarTitle(searchKey);
    CommonUtils.showDialog(getActivity(), "Searching...", false);
    getGadget(searchKey);
}
/**
 *
 * @param menu
 * @param inflater
 */
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    //the button search is setting to visible
    menu.findItem(R.id.action_search).setVisible(true);
    menu.findItem(R.id.action_share).setVisible(false);
    super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar actions click
    switch (item.getItemId()) {
        case R.id.action_search:
            isSearchMode = true;
            //Log.d("billy","inside action_search");
            rightHeaderButtonClick();
            return true;
        //how working
        case R.id.action_share:
            return false;
        default:
            return super.onOptionsItemSelected(item);
    }
}
/**
 * showing the text box
 */
public void rightHeaderButtonClick() {
    if (ln_search.isShown()) {
        ln_search.setVisibility(View.GONE);
        showKeyboard(false);
    } else {
        ln_search.setVisibility(View.VISIBLE);
        ed_search.requestFocus();
        showKeyboard(true);
        //Log.d("bill", "rightHeaderButtonClick - open ln_search");
    }
}
/**
 * showing the keyboard
 * @param isShow
 */
public void showKeyboard(boolean isShow) {
    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Service.INPUT_METHOD_SERVICE);
    if (isShow) {
        // show keyboard
        imm.showSoftInput(ed_search, 0);
    } else {
        // hide keyboard
        imm.hideSoftInputFromWindow(ed_search.getWindowToken(), 0);
    }
}

Thanks in advance!

Upvotes: 2

Views: 4748

Answers (2)

Walle
Walle

Reputation: 41

I had a similar situation wherein I had search in the child fragment of the navigation drawer.

Now on searching the keyboard would pop up and when I wanted to click on the navigation drawer again the keyboard wouldn't hide so I mixed up the 2 solution above and came up with this.

mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.app_name, R.string.app_name) {

@Override
    public void onDrawerSlide(View drawerView, float slideOffset){
        hideKeyboard(true, ActivityName);
        }
};

public static void hideKeyboard(boolean val, Activity activity) {
    View view;
    view = activity.getWindow().getCurrentFocus();
        if (val == true) {
            InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

and guess what this worked! thanks for your help!

Upvotes: 2

Aditya Chauhan
Aditya Chauhan

Reputation: 271

use this

 public static void showKeyboard(Activity pActivity, View pView) {
    if (pView == null) {
        pView = pActivity.getWindow().getCurrentFocus();
    } else {
        /**
         * For {@link EditText}, a call to {@link View#requestFocus()} will
         * open the keyboard as per inputType set for {@link EditText}
         */
        pView.requestFocus();
    }
    if (pView != null) {
        InputMethodManager imm = (InputMethodManager) pActivity
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.showSoftInput(pView, InputMethodManager.SHOW_FORCED);
        }
    }
}


public static void hideKeyboard(View pView, Activity pActivity) {
    if (pView == null) {
        pView = pActivity.getWindow().getCurrentFocus();
    }
    if (pView != null) {
        InputMethodManager imm = (InputMethodManager) pActivity
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(pView.getWindowToken(), 0);
        }
    }
}

Upvotes: 4

Related Questions