防止AlertDialog中EditText自动聚焦

5
我遇到了一些问题,无法阻止AlertDialog中的EditText自动获得焦点并显示键盘。
在呈现的活动中,windowSoftInputMode = stateHidden,并且当活动加载时,其中的EditText不会获得焦点。但是当对话框显示时,键盘会自动出现。
我该如何防止AlertDialog在显示时显示键盘?

设置属性 android:focusable="true" 和 android:focusableInTouchMode="true"。 - RajaReddy PolamReddy
3个回答

17

如果您为 AlertDialog 设计了自定义布局,您可以使用一个虚拟视图来获取焦点而不是使用您的 edittext:

<!-- Dummy view -->
<View
    android:layout_width="0dp" 
    android:layout_height="0dp"
    android:focusable="true" 
    android:focusableInTouchMode="true"/>
尝试将该视图放在您的编辑框之前。

遇到了同样的问题数百次,总是很烦人 :D。很高兴它能帮到你。 - AlexBalo
请注意,仅使用 focusable="true" 是不够的。 - Bojan Radivojevic
1
尽管这是最好和最简单的解决方案,但仍然有点像黑客。xD - 000000000000000000000
是的,这绝对是一个hack。不过,如果你的EditText在像LinearLayout这样的控件内部,你可以在那个LinearLayout上设置focusablefocusableInTouchMode属性,而不是添加一个“Dummy view”。 - Anthony Chuinard

0

在创建您的编辑文本时,请使用以下内容

 <EditText
           android:id="@+id/E_table_no"
           android:layout_width="0dp"
           android:layout_height="38dp"
           android:layout_weight="1"
           android:focusableInTouchMode="false"
           android:imeOptions="flagNoExtractUi"
           android:singleLine="true"
           android:windowSoftInputMode="stateHidden" />

-1
使用下面的代码强制隐藏Android软键盘。
EditText myEditText = (EditText) findViewById(R.id.myEditText);  
InputMethodManager imm = (InputMethodManager)getSystemService(
      Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接