how to get Activity's windowToken without view?

后端 未结 7 1092
南方客
南方客 2021-02-01 14:38

Now, I try to hide the softkeyboard when user touch outside the keyboard:

((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(         


        
相关标签:
7条回答
  • 2021-02-01 14:59

    I faced exactly the same problem, while writing OnPageChangeListener within an Activity. You can use one of these solutions. Either:

    getWindow().getDecorView().getRootView().getWindowToken()   
    

    or:

    findViewById(android.R.id.content).getWind‌​owToken()
    
    0 讨论(0)
  • 2021-02-01 15:05

    In kotlin:

    val imm  = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(window.attributes.token, 0)
    

    Or, If you have a view:

    imm.hideSoftInputFromWindow(view.windowToken, 0)
    
    0 讨论(0)
  • 2021-02-01 15:13

    Simply use getWindow().getDecorView().getWindowToken()

    0 讨论(0)
  • 2021-02-01 15:17

    Surely you can use:

    getContentView().getWindowToken()
    

    or you can refer to SO Quest

    0 讨论(0)
  • 2021-02-01 15:21

    You could just get the token from the WindowManager.LayoutParams of the window directly

    getWindow().getAttributes().token
    
    0 讨论(0)
  • 2021-02-01 15:21
    public static final String M_TOKEN = "mToken";
    
    @Nullable
    protected IBinder getToken(Activity activity) {
        try {
            Field mTokenField = Activity.class.getDeclaredField(M_TOKEN);
            mTokenField.setAccessible(true);
            IBinder mToken = (IBinder) mTokenField.get(activity);
            return mToken;
        } catch (NoSuchFieldException e) {
            // handle 
        } catch (IllegalAccessException e) {
           // handle
        }
        return null;
    }
    
    0 讨论(0)
提交回复
热议问题