我在Android中有一个活动,包含两个元素:
编辑文本列表视图
当“活动”启动时,EditText立即具有输入焦点(闪烁光标)。我不希望任何控件在启动时具有输入焦点。我尝试了:
EditText.setSelected(false);
EditText.setFocusable(false);
没有运气。如何说服EditText在“活动”启动时不选择自己?
我在Android中有一个活动,包含两个元素:
编辑文本列表视图
当“活动”启动时,EditText立即具有输入焦点(闪烁光标)。我不希望任何控件在启动时具有输入焦点。我尝试了:
EditText.setSelected(false);
EditText.setFocusable(false);
没有运气。如何说服EditText在“活动”启动时不选择自己?
当前回答
简单可靠的解决方案,只需重写此方法:
@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);
}
}
其他回答
<EditText
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="@+id/etComments"
android:hint="Comments.."
android:textSize="14dp"
android:focusable="false"
android:textStyle="italic"/>
我找到的唯一解决方案是:
创建LinearLayout(我不知道其他类型的Layout是否有效)设置属性android:focusable=“true”和android:focuableInTouchMode=“true“
并且EditText在开始活动后无法获得焦点
做这个,完成你的工作!
android:focusable="true"
android:focusableInTouchMode="true"
您可以通过创建布局宽度和高度设置为0dp的虚拟EditText,并请求对该视图进行聚焦来实现这一点。在xml布局中添加以下代码段:
<EditText
android:id="@+id/editText0"
android:layout_width="0dp"
android:layout_height="0dp"
android:hint="@string/dummy"
android:ems="10"
>
<requestFocus />
</EditText>
当按下按钮时,我使用以下代码阻止EditText窃取焦点。
addButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
View focused = internalWrapper.getFocusedChild();
focused.setVisibility(GONE);
v.requestFocus();
addPanel();
focused.setVisibility(VISIBLE);
}
});
Basically, hide the edit text and then show it again. This works for me as the EditText is **not** in view so it doesn't matter whether it is showing.
You could try hiding and showing it in succession to see if that helps it lose focus.