Xamarin Android(C#)自定义键盘后如何隐藏并永久禁用系统键盘?
在Xamarin Android(C#)中隐藏并永久禁用系统键盘的实现方案
一、临时隐藏已弹出的系统软键盘
如果需要快速隐藏当前显示的系统键盘,可在Activity中执行以下代码:
var inputMethodManager = (InputMethodManager)GetSystemService(InputMethodService); inputMethodManager.HideSoftInputFromWindow(CurrentFocus.WindowToken, HideSoftInputFlags.None);
也可针对特定输入控件,在其获取焦点时触发隐藏:
yourEditText.FocusChange += (s, e) => { if (e.HasFocus) { var imm = (InputMethodManager)GetSystemService(InputMethodService); imm.HideSoftInputFromWindow(yourEditText.WindowToken, HideSoftInputFlags.None); } };
二、永久禁用单个输入控件的系统键盘
要让指定输入控件(如EditText)永远不触发系统键盘弹出,有两种可靠实现方式:
方式1:直接设置控件属性
在AXML布局文件中为目标控件添加以下属性:
android:focusable="true" android:focusableInTouchMode="true" android:inputType="none"
或在C#代码中动态设置:
yourEditText.InputType = Android.Text.InputTypes.Null; yourEditText.Focusable = true; yourEditText.FocusableInTouchMode = true;
这样控件可正常获取焦点,同时不会唤起系统键盘,完美适配自定义数字键盘的交互需求。
方式2:自定义EditText子类
若需在多个页面复用禁用逻辑,可自定义EditText子类,重写OnCreateInputConnection方法阻止系统输入法连接:
public class NoSystemKeyboardEditText : EditText { public NoSystemKeyboardEditText(Context context) : base(context) { } public NoSystemKeyboardEditText(Context context, IAttributeSet attrs) : base(context, attrs) { } public NoSystemKeyboardEditText(Context context, IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr) { } public override IInputConnection OnCreateInputConnection(EditorInfo outAttrs) { // 返回null切断与系统输入法的连接 return null; } }
后续在布局或代码中使用该自定义控件即可彻底禁用系统键盘。
三、全局禁用系统键盘(应用级)
若需整个应用内都禁用系统键盘,可在每个Activity的DispatchTouchEvent中统一处理,确保任何交互下都隐藏键盘:
public override bool DispatchTouchEvent(MotionEvent ev) { if (CurrentFocus != null) { var imm = (InputMethodManager)GetSystemService(InputMethodService); imm.HideSoftInputFromWindow(CurrentFocus.WindowToken, HideSoftInputFlags.None); } return base.DispatchTouchEvent(ev); }
同时确保所有输入控件都使用上述单个控件的禁用方案,即可实现全局禁用效果。
内容的提问来源于stack exchange,提问作者Julio Adames
相关产品推荐
相关产品推荐

