我在Android中有一个活动,包含两个元素:
编辑文本列表视图
当“活动”启动时,EditText立即具有输入焦点(闪烁光标)。我不希望任何控件在启动时具有输入焦点。我尝试了:
EditText.setSelected(false);
EditText.setFocusable(false);
没有运气。如何说服EditText在“活动”启动时不选择自己?
我在Android中有一个活动,包含两个元素:
编辑文本列表视图
当“活动”启动时,EditText立即具有输入焦点(闪烁光标)。我不希望任何控件在启动时具有输入焦点。我尝试了:
EditText.setSelected(false);
EditText.setFocusable(false);
没有运气。如何说服EditText在“活动”启动时不选择自己?
当前回答
问题似乎来自我只能在布局的XML形式中看到的属性。
确保在EditText XML标记中删除声明末尾的此行:
<requestFocus />
这应该是这样的:
<EditText
android:id="@+id/emailField"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress">
//<requestFocus /> /* <-- without this line */
</EditText>
其他回答
请尝试clearFocus()而不是setSelected(false)。Android中的每个视图都具有可聚焦性和可选择性,我认为您只需要清除焦点。
这些解决方案都不适合我。我修复自动对焦的方法是:
<activity android:name=".android.InviteFriendsActivity"
android:windowSoftInputMode="adjustPan">
<intent-filter >
</intent-filter>
</activity>
这是最完美、最简单的解决方案。我总是在我的应用程序中使用这个。getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
简单可靠的解决方案,只需重写此方法:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
View v = getCurrentFocus();
if (v != null &&
(ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) &&
v instanceof EditText &&
!v.getClass().getName().startsWith("android.webkit.")) {
int scrcoords[] = new int[2];
v.getLocationOnScreen(scrcoords);
float x = ev.getRawX() + v.getLeft() - scrcoords[0];
float y = ev.getRawY() + v.getTop() - scrcoords[1];
if (x < v.getLeft() || x > v.getRight() || y < v.getTop() || y > v.getBottom())
hideKeyboard(this);
}
return super.dispatchTouchEvent(ev);
}
public static void hideKeyboard(Activity activity) {
if (activity != null && activity.getWindow() != null && activity.getWindow().getDecorView() != null) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0);
}
}
我找到的唯一解决方案是:
创建LinearLayout(我不知道其他类型的Layout是否有效)设置属性android:focusable=“true”和android:focuableInTouchMode=“true“
并且EditText在开始活动后无法获得焦点