一、通过布局文件实现自动隐藏软键盘
在布局文件的根标签中加入以下属性:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusableInTouchMode="true">
其中,android:focusableInTouchMode="true"是用来在布局文件加载时自动隐藏软键盘,让用户能够通过点击屏幕其他区域来隐藏软键盘。
如果想通过按钮点击等方式来控制软键盘显示和隐藏,可以在对应的View中添加onClick()方法,利用InputMethodManager来控制软键盘的显示和隐藏。
EditText editText = findViewById(R.id.editText); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(editText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
二、通过代码实现动态隐藏软键盘
在代码中调用InputMethodManager的hideSoftInputFromWindow()方法来隐藏软键盘。
EditText editText = findViewById(R.id.editText); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(editText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
其中,需要传入当前EditText的WindowToken参数,以表明需要隐藏的软键盘是哪一个。
三、通过自定义控件实现更加灵活的软键盘控制
自定义控件可以让开发人员根据实际需求来实现更加灵活的软键盘控制,比如点击EditText时自动弹出软键盘,点击其他区域或按下返回键时自动隐藏软键盘等等。
需要在自定义控件的代码中实现OnTouchListener和OnFocusChangeListener等接口,以实现软键盘的显示和隐藏。
public class CustomEditText extends EditText implements View.OnTouchListener, View.OnFocusChangeListener {
private Context context;
public CustomEditText(Context context) {
super(context);
init(context);
}
public CustomEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public CustomEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
this.context = context;
setOnTouchListener(this);
setOnFocusChangeListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
showSoftKeyboard();
return true;
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideSoftKeyboard();
}
}
private void showSoftKeyboard() {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT);
}
private void hideSoftKeyboard() {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
需要注意的是,在使用自定义控件的时候需要在布局文件中引入该控件,而不是普通的EditText。
<com.example.myapplication.CustomEditText
android:id="@+id/customEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
四、总结
本文介绍了三种实现Android软键盘隐藏的方式,其中第一种是在布局文件中添加属性来自动隐藏软键盘,第二种是通过代码动态控制软键盘的显示和隐藏,第三种是通过自定义控件实现更加灵活的软键盘控制。
开发人员可以根据实际需求来选择不同的实现方式,以便更好地满足用户的交互体验。
原创文章,作者:FKZW,如若转载,请注明出处:https://www.506064.com/n/132122.html
微信扫一扫
支付宝扫一扫