-1

I have an Activity with Tabs set up with a ViewPager, in one of the Fragments there's an EditText which opens soft input keyboard when the Activity starts, which isn't something I want. I've been trying to hide it but when I'm trying to get a WindowToken it's always null -- on the EditText itself, on the root view of the Fragment, on the ContentView of the parent activity (I tried findViewById(android.R.id.content) with and without getDecorView(), with and without getRootView()), on every View I get from ContentView with getChildAt(). getCurrentFocus() also returns null. Also, I tried getting the parent Activity both from getActivity() and from a reference I keep in my Application class, and they work the same.

My ultimate goal is to hide the keyboard, or not show it at all unless the user explicitly calls it. If I have to find a way to get a WindowToken for that, I'd like to do that, but if there's another way to hide the keyboard, I'll be happy to try that too.

I'd like to know why the question was downvoted. I can't improve it if I don't know the reason.

Bits of related code:

activity_main.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:fitsSystemWindows="true"
    android:background="@color/windowBackground"
    tools:openDrawer="start">

<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<include
    layout="@layout/drawer" />

</android.support.v4.widget.DrawerLayout>

app_bar_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.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"
xmlns:fresco="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.company.app.activities.MainActivity">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:elevation="4dp"
    android:theme="@style/AppTheme.AppBarOverlay">

    ...

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/underline_grey"
        app:tabMode="scrollable"
        app:tabGravity="center"
        app:popupTheme="@style/AppTheme.PopupOverlayBg"/>

</android.support.design.widget.AppBarLayout>
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:scrollbars="vertical"
    android:orientation="vertical"
    app:layout_anchor="@+id/appbar_layout"
    android:fillViewport="true">
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <include
            layout="@layout/bg"
            android:layout_width="match_parent"
            android:layout_height="800dp" />
    <include
        android:id="@+id/pager_frame"
        layout="@layout/content_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/></FrameLayout>
</ScrollView>
</android.support.design.widget.CoordinatorLayout>

(before anyone says anything, the Scroll wasn't my idea)

content_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.company.app.activities.MainActivity"
tools:showIn="@layout/app_bar_main">

<android.support.v4.view.ViewPager
    android:id="@+id/main_page_pager"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

fragment_get_bonuses.xml:

<android.support.constraint.ConstraintLayout
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"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
android:orientation="vertical"
android:gravity="center"
tools:context="com.company.app.fragments.GetBonusesFragment">

...

<android.support.v7.widget.CardView
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/guideline50"
app:layout_constraintBottom_toTopOf="@+id/guideline70"
card_view:contentPadding="4dp"
card_view:cardUseCompatPadding="true"
card_view:cardElevation="4dp"
card_view:cardCornerRadius="10dp"
card_view:cardBackgroundColor="@color/windowBackground"
android:layout_span="6">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:padding="4dp"
    android:gravity="center"
    android:weightSum="1">
    <EditText
        android:id="@+id/bonuses_code_edit"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:layout_weight=".5"
        android:padding="8dp"
        android:layout_marginRight="4dp"
        android:background="@drawable/border_grey"
        android:hint="xxxx-xxxx-xxxx"
        android:maxLines="1"
        android:lines="1"
        android:inputType="text"
        android:nextFocusForward="@+id/bonuses_code_card"/>
    <android.support.v7.widget.CardView
        android:id="@+id/bonuses_code_card"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="4dp"
        card_view:contentPadding="0dp"
        card_view:cardUseCompatPadding="false"
        card_view:cardElevation="4dp"
        card_view:cardCornerRadius="10dp"
        card_view:cardBackgroundColor="@color/pinkAcivateCode"
        android:layout_weight=".5"
        android:clickable="true"
        android:onClick="onMenuButtonsClick">
        <TextView
            android:id="@+id/bonuses_code_button"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="@string/activate_code"
            android:textColor="@color/textColorPrimary"
            android:lines="2"
            android:padding="8dp" />
    </android.support.v7.widget.CardView>
</LinearLayout>
</android.support.v7.widget.CardView>
...

<android.support.constraint.Guideline
android:id="@+id/guideline50"
android:layout_width="1dp"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5"
tools:layout_editor_absoluteY="0dp"
tools:layout_editor_absoluteX="0dp" />

<android.support.constraint.Guideline
android:id="@+id/guideline70"
android:layout_width="1dp"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.7"
tools:layout_editor_absoluteY="0dp"
tools:layout_editor_absoluteX="0dp" />

...

</android.support.constraint.ConstraintLayout>

MainActivity.java:

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

AppCompatActivity context;

...

TabLayout mainPageTabs;

View pagerView;
ViewPager mainPagePager;
MainPageTabsAdapter adapter;

TextView tabBonuses;
...

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Fresco.initialize(this);
    setContentView(R.layout.activity_main);
    context = this;
    App.getContext().setCurrent(context); // saves reference to currently running Activity in Application class
    ...

    pagerView = findViewById(R.id.pager_frame);
    mainPageTabs = (TabLayout) findViewById(R.id.tabs);
    ...
    setupMainTabs();
}

public void setupMainTabs(){
    if (mainPagePager == null) mainPagePager = (ViewPager) findViewById(R.id.main_page_pager);
    if (mainPageTabs == null) mainPageTabs = (TabLayout) findViewById(R.id.tabs);
    setupMainPageViewPager(mainPagePager);
    mainPageTabs.setupWithViewPager(mainPagePager,true);
    ...

    tabBonuses = (TextView) LayoutInflater.from(this).inflate(R.layout.tab_item, null); // TextView with a background
    tabBonuses.setText(getText(R.string.collect_bonuses));
    ...
    mainPageTabs.getTabAt(0).setCustomView(tabBonuses);
    ...
//        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//        imm.hideSoftInputFromWindow(findViewById(R.id.pager_frame).getWindowToken(), 0);
}

private void setupMainPageViewPager(ViewPager viewPager) {
    adapter = new MainPageTabsAdapter(getSupportFragmentManager(),this);
    viewPager.setAdapter(adapter);
    viewPager.setOffscreenPageLimit(2);
}

...

@Override
protected void onResume() {
    super.onResume();
    App.getContext().setCurrent(context);
    ...
//        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//        imm.hideSoftInputFromWindow(findViewById(R.id.pager_frame).getWindowToken(), 0);
}

...

}

Application class:

...
private static App context;
private AppCompatActivity current;
...
@Override
public void onCreate() {
    super.onCreate();
    if (context == null) context = (DreamClub) getApplicationContext();
    ...
}
...

public void setCurrent(AppCompatActivity a) {
    current = a;
}

public Activity getCurrent(){return current;}
...

public static App getContext() {
    if (context == null) context = new DreamClub();
    return context;
}

MainPageTabsAdapter.java:

public class MainPageTabsAdapter extends FragmentPagerAdapter {

Context context;

ArrayList<Fragment> fragmList;
ArrayList<String> titleList;

public MainPageTabsAdapter(FragmentManager fm, Context context) {
    super(fm);
    this.context = context;
    fragmList = new ArrayList<>();
    fragmList.add(new GetBonusesFragment());
    ...
    titleList = new ArrayList<>();
    titleList.add(context.getString(R.string.collect_bonuses));
    ...
}

@Override
public Fragment getItem(int position) {
    return fragmList.get(position);
}

...

@Override
public CharSequence getPageTitle(int position) {
    return titleList.get(position);
}
}

GetBonusesFragment.java:

public class GetBonusesFragment extends Fragment {

EditText codeEdit;
View root;

...

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    root = inflater.inflate(R.layout.fragment_get_bonuses, container, false);
    ...
    codeEdit = (EditText) root.findViewById(R.id.bonuses_code_edit);
//        InputMethodManager imm = (InputMethodManager)(getActivity().getSystemService(Context.INPUT_METHOD_SERVICE));
//        codeEdit.requestFocus();
//        imm.hideSoftInputFromWindow(codeEdit.getWindowToken(), 0);
    ...
//        codeEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
//                if (hasFocus) {
//                    InputMethodManager imm = (InputMethodManager)(getActivity().getSystemService(Context.INPUT_METHOD_SERVICE));
//                    imm.showSoftInput(root,0)/*hideSoftInputFromWindow(root.getWindowToken(), 0)*/;
//                }
//                else {
//                    Log.v("!!!called","on focus change: false");
//                    InputMethodManager imm = (InputMethodManager)(getActivity().getSystemService(Context.INPUT_METHOD_SERVICE));
//                    imm.hideSoftInputFromWindow(root.getWindowToken(), 0);
//                }
//            }
//        });
    ...
    InputMethodManager imm = (InputMethodManager)(getActivity().getSystemService(Context.INPUT_METHOD_SERVICE));
    imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY,0);
//        try {
//            InputMethodManager imm = (InputMethodManager)(getActivity().getSystemService(Context.INPUT_METHOD_SERVICE));
//            imm.hideSoftInputFromWindow(DreamClub.getContext().getCurrent().getCurrentFocus().getWindowToken(), 0);
//        }
//        catch (Exception e) {
//            try {
//                InputMethodManager imm = (InputMethodManager)(getActivity().getSystemService(Context.INPUT_METHOD_SERVICE));
//                imm.hideSoftInputFromWindow(DreamClub.getContext().getCurrent().getWindow().findViewById(android.R.id.content).getRootView().getWindowToken(), 0);
//            }
//            catch (Exception e1) {
//                if (DreamClub.getContext().getCurrent().getWindow().findViewById(android.R.id.content).getRootView() != null && ((ViewGroup)getActivity().getWindow().findViewById(android.R.id.content).getRootView()).getChildCount() > 0) {
//                    for (int i = 0; i < ((ViewGroup)DreamClub.getContext().getCurrent().getWindow().findViewById(android.R.id.content).getRootView()).getChildCount(); i++) {
//                        if (((ViewGroup)DreamClub.getContext().getCurrent().getWindow().findViewById(android.R.id.content).getRootView()).getChildAt(i).getWindowToken() != null) {
//                            InputMethodManager imm = (InputMethodManager)(getActivity().getSystemService(Context.INPUT_METHOD_SERVICE));
//                            imm.hideSoftInputFromWindow(((ViewGroup)DreamClub.getContext().getCurrent().getWindow().findViewById(android.R.id.content).getRootView()).getChildAt(i).getWindowToken(), 0);
//                            break;
//                        }
//                    }
//                }
//            }
//        }
//        root.findViewById(codeEdit.getNextFocusForwardId()).requestFocus();
//        root.findViewById(R.id.bonuses_wallets).requestFocus();
//        if (codeEdit.hasFocus()) {
//            codeEdit.clearFocus();
//        }
//        InputMethodManager imm = (InputMethodManager)(getActivity().getSystemService(Context.INPUT_METHOD_SERVICE));
//        imm.hideSoftInputFromWindow(codeEdit.getWindowToken(), 0);
//        imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
    return root;
}

//    @Override
//    public void onResume() {
//        super.onResume();
//        InputMethodManager imm = (InputMethodManager)(DreamClub.getContext().getCurrent().getSystemService(Context.INPUT_METHOD_SERVICE));
//        imm.hideSoftInputFromWindow(codeEdit.getWindowToken(), 0);
//    }
}
Kaworu
  • 210
  • 2
  • 13

2 Answers2

1

Just add this in your manifest activity

android:windowSoftInputMode="stateHidden"

<activity
            android:name=".activity.SignupActivity"

            android:windowSoftInputMode="stateHidden" />
jagapathi
  • 1,559
  • 1
  • 16
  • 29
0

Add this in your manifest file

 <activity android:name="com.your.package.ActivityName"
  android:windowSoftInputMode="stateHidden"  />

or try

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)‌;

But if your requirement like hide keyborad on Button click or backPressed then use like this

public static void HideKeyboard(Context context, View view) {
    if (view == null) {
        return;
    }
    InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
    if (!imm.isActive()) {
        return;
    }
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

and please more follow this link

How to hide Soft Keyboard when activity starts

Dileep Patel
  • 1,912
  • 2
  • 9
  • 26