我在Android中有一个活动,包含两个元素:

编辑文本列表视图

当“活动”启动时,EditText立即具有输入焦点(闪烁光标)。我不希望任何控件在启动时具有输入焦点。我尝试了:

EditText.setSelected(false);
EditText.setFocusable(false);

没有运气。如何说服EditText在“活动”启动时不选择自己?


当前回答

只需在EditText的父布局中添加android:focuableInTouchMode=“true”,您就可以摆脱这种尴尬的行为。

其他回答

简单的解决方案:在活动标签中的AndroidManifest中使用

android:windowSoftInputMode="stateAlwaysHidden"

在Activity的onCreate中,只需在EditText元素上添加useclearFocus()。例如

edittext = (EditText) findViewById(R.id.edittext);
edittext.clearFocus();

如果您想将焦点转移到另一个元素,请使用requestFocus()。例如

button = (Button) findViewById(R.id.button);
button.requestFocus();

简单可靠的解决方案,只需重写此方法:

@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);
    }
}

在onCreate方法中添加以下内容:

this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

您可以通过使用请求焦点并使用键盘隐藏代码来指定其他小部件的焦点。