您当前的位置: 首页 >  ui

命运之手

暂无认证

  • 0浏览

    0关注

    747博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【Android】【UI】软键盘弹出隐藏,兼容弹窗

命运之手 发布时间:2021-10-21 17:01:29 ,浏览量:0

InputMethodManager和Window

关于软键盘的博客网上很多,但是很多没有提及一点

就是输入法的布局是绑定在Window上的

当我们的界面只有ActivityWindow时,网上的博客都是没问题的

但是如果界面布局是展示在Dialog,DialogFragment,PopupWindow里面的

网上的很多博客,其实是不生效的,正规的方法如下

代码


    //打开软键盘
    public static void openKeyboard(EditText edit) {
        MainThread.postLater(() -> {
            InputMethodManager manager = edit.getContext().getSystemService(InputMethodManager.class);
            manager.toggleSoftInputFromWindow(edit.getWindowToken(), 0, 0);
        }, 200);
    }

    //关闭软键盘
    public static void closeKeyboard(EditText edit) {
        InputMethodManager manager = edit.getContext().getSystemService(InputMethodManager.class);
        manager.toggleSoftInputFromWindow(edit.getWindowToken(), 0, 0);
    }


	//监听窗口绑定状态
	contentEdit.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
	    @Override
	    public void onViewAttachedToWindow(View v) {
	        contentEdit.requestFocus();
	        contentEdit.setSelection(contentEdit.getText().length());
	        Services.openKeyboard(contentEdit);
	    }
	
	    @Override
	    public void onViewDetachedFromWindow(View v) {
	        contentEdit.clearFocus();
	        Services.closeKeyboard(contentEdit);
	    }
	});

由于onViewAttachedToWindow,比Window实际显示,会早一点点

所以openKeyboard需要通过Handler延时几百毫秒再执行

openKeyboard方法一定要确保Window已经显示了,才会执行生效

getWindowToken方法可以获取到View所在Window对应的Binder

通过这个Binder,就可以控制当前Window的输入法布局

关注
打赏
1654938663
查看更多评论
立即登录/注册

微信扫码登录

0.0419s