首页 技术 正文
技术 2022年11月18日
0 收藏 643 点赞 3,883 浏览 1507 个字

在Android的Activity放置EditText之后,如果没有做特别的调整,每次一进入Activity,EditText都会自动取得焦点,然后弹出虚拟键盘,造成画面变得拥挤。虽然Android这样的设计是为了减少使用者点击萤幕的次数,但是并不是在所有情况下一进入Activity都需要自动弹出虚拟键盘,使用者可能只是要看资料而已(例如看聊天讯息)。

进入含有EditText的Activity时,不自动弹出虚拟键盘

解决一进入Activity就自动弹出虚拟键盘
只要在Activity的onCreate阶段,加上以下程式码即可。

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

或是在AndroidManifest.xml中,设定Activity的android:windowSoftInputMode属性,如下:

<activity
android:name="org.magiclen.TestActivity"
android:label="@string/app_name"
android:windowSoftInputMode="stateHidden" />

设定windowSoftInputMode属性为State Hidden之后,进入Activity时,EditText依然会取得焦点,但不会立刻弹出虚拟键盘,还要再点击一次EditText才会弹出键盘。问题成功解决了!

解决一弹出Dialog又再自动弹出虚拟键盘
Dialog中若有EditText,也会遇到和Activity一样,在出现Dialog的同时又再自动弹出虚拟键盘的状况。解决方法跟Activity相同,取得Dialog的Window后,使用setSoftInputMode方法来设定隐藏键盘,程式码如下:

AlertDialog dialog = new AlertDialog.Builder(this).setView(editText).create();
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
dialog.show();

Android中点击空白处隐藏软键盘

InputMethodManager imm= (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_DOWN) {
System.out.println("down");
if (RegisterActivity.this.getCurrentFocus() != null) {
if (RegisterActivity.this.getCurrentFocus().getWindowToken() != null) {
imm.hideSoftInputFromWindow(RegisterActivity.this.getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
return super.onTouchEvent(event);
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,105
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,582
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,429
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,200
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,836
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,919