编辑框请求焦点

61

我正在设计一个登录页面,如下所示:

UserName:  .....

Password:  .....

     LoginButton
当活动开始时,我希望焦点转到“UserName”文本框并出现键盘。 我正在使用以下代码:
    boolean checkFocus=user.requestFocus();
    Log.i("CheckFocus", ""+checkFocus);
    if(checkFocus==true)
    {
    InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    mgr.showSoftInput(user, InputMethodManager.SHOW_IMPLICIT);
    }

我不明白在哪里编写代码才能使键盘在活动启动时出现,并将焦点放在“UserName”编辑框上。请问有人可以指导我吗?

8个回答

192

通过编程实现:

edittext.requestFocus();

通过xml:

<EditText...>
    <requestFocus />
</EditText>

或者手动调用 onClick 方法。


在Android应用程序中设置初始焦点,不要在Layout XML中声明编辑文本。 - Awais Tariq
你在测试哪个设备?有时候,即使在焦点上,Android操作系统也不会在活动开始后打开键盘。这种情况经常发生在小屏幕设备上。实际上,操作系统智能地检测屏幕大小,并决定是否显示键盘。另一件你可以尝试的事情是手动调用你的编辑文本框的onclick监听器...像:editText.onClick(null); 并且在onClick监听器中进行检查以处理空事件(即防止应用程序崩溃)。 - Awais Tariq
我正在HTC Desire上进行测试。 - Kanika
不,那还是不行。你告诉我一个事情,当我的活动开始时,它会首先创建XML文件并使用setContentView()方法。 - Kanika
让我们在聊天中继续这个讨论。 (http://chat.stackoverflow.com/rooms/4873/discussion-between-awais-tariq-and-kanika) - Awais Tariq
在这个语句之后,我设置了user.requestfocus(),为什么它没有显示QWERTY键盘? - Kanika

26

是的,我得到了答案...只需简单地编辑manifest文件即可:

        <activity android:name=".MainActivity"
        android:label="@string/app_name"
        android:windowSoftInputMode="stateAlwaysVisible" />

onCreate()中调用EditText.requestFocus()方法设置焦点。

谢谢。


这应该是被接受的答案,它是唯一对我有用的!谢了,伙计。 - Stillie

6

从activity中调用youredittext.requestFocus()

oncreate();

并将上述代码粘贴到那里使用


user =(EditText)findViewById(R.id.editText1); pass =(EditText)findViewById(R.id.editText2); - Kanika
我尝试过了,但是没有起作用。我已经在这些行后面添加了我的代码。 - Kanika
https://dev59.com/n2445IYBdhLWcg3w3Nsf - drooooooid

1

软键盘被禁用(只允许使用外部键盘),我通过将光标移动到EditText末尾来解决了这个问题:

editText.setSelection(editText.getText().length)

0

我知道现在已经太晚了,但唯一对我有效的解决方案是

edittext.requestFocus()   
edittext.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(),MotionEvent.ACTION_DOWN,0f,0f,0))    
edittext.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(),MotionEvent.ACTION_UP,0f,0f,0))

我使用这个来编程地打开键盘。


0

2023 年我完美地使用了这个。

在清单文件中添加以下行以打开要使用键盘的活动。

android:windowSoftInputMode="stateVisible"

在 Activity/Fragment 中添加以下内容:

 if (editText.text.isNullOrEmpty()) {
            editText.requestFocus()
        }

如果您不添加此if语句,键盘也会在活动恢复状态下打开。


0

你可以这样编写代码:

if (TextUtils.isEmpty(username)) {
    editTextUserName.setError("Please enter username");
    editTextUserName.requestFocus();
    return;
}

if (TextUtils.isEmpty(password)) {
    editTextPassword.setError("Enter a password");
    editTextPassword.requestFocus();
    return;
}

0

在Manifest中设置Activity:

android:windowSoftInputMode="adjustResize"

当视图准备好时,设置焦点:

fun setFocus(view: View, showKeyboard: Boolean = true){
    view.post {
        if (view.requestFocus() && showKeyboard)
            activity?.openKeyboard() // call extension function
    }
}

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