如何以编程方式在EditText上设置焦点(并显示键盘)

时间:2012-01-24 17:45:29

标签: android focus android-edittext

我的布局包含一些像这样的视图:

<LinearLayout>
<TextView...>
<TextView...>
<ImageView ...>
<EditText...>
<Button...>
</linearLayout>

如何以编程方式在EditText上设置焦点(显示键盘)?

我已尝试过此功能,只有在我正常启动Activity时才有效,但是当我在TabHost启动它时,它无效。

txtSearch.setFocusableInTouchMode(true);
txtSearch.setFocusable(true);
txtSearch.requestFocus();

15 个答案:

答案 0 :(得分:296)

试试这个:

EditText editText = (EditText) findViewById(R.id.myTextViewId);
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);

http://developer.android.com/reference/android/view/View.html#requestFocus()

答案 1 :(得分:143)

使用:

editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

答案 2 :(得分:40)

这对我有用, 感谢ungalcrys

显示键盘:

editText = (EditText)findViewById(R.id.myTextViewId);
editText.requestFocus();
InputMethodManager imm = (InputMethodManager)getSystemService(this.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_IMPLICIT_ONLY);

隐藏键盘:

InputMethodManager imm = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);

答案 3 :(得分:36)

showSoftInput根本不适合我。

我想我需要设置输入模式:android:windowSoftInputMode="stateVisible"(此处在清单中的活动组件中)

希望这有帮助!

答案 4 :(得分:26)

final EditText tb = new EditText(this);
tb.requestFocus();
tb.postDelayed(new Runnable() {
    @Override
    public void run() {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInput(tb, InputMethodManager.SHOW_IMPLICIT);
    }
}, 1000);

答案 5 :(得分:7)

以下是如何使用kotlin扩展来显示和隐藏软键盘:

fun View.showKeyboard() {
  this.requestFocus()
  val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
  inputMethodManager.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}

fun View.hideKeyboard() {
  val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
  inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}

然后你可以这样做:

editText.showKeyboard()
// OR
editText.hideKeyboard()

答案 6 :(得分:1)

这是用于隐藏和显示键盘的KeyboardHelper类

import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

/**
 * Created by khanhamza on 06-Mar-17.
 */

public class KeyboardHelper {

    public static void hideSoftKeyboard(Context context, View view) {
        if (context == null) {
            return;
        }

        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);

    }

    public static void hideSoftKeyboard(Context context, EditText editText) {

        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }


    public static void openSoftKeyboard(Context context, EditText editText) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
    }

}

答案 7 :(得分:1)

我尝试了戴维·梅里曼(David Merriman)给出的最高答案,但在我的情况下也没有用。但是我发现运行此代码的建议被延迟了here,它的工作就像一个魅力。

val editText = view.findViewById<View>(R.id.settings_input_text)

editText.postDelayed({
    editText.requestFocus()

    val imm = context.getSystemService(INPUT_METHOD_SERVICE) as? InputMethodManager
    imm?.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT)
}, 100)

答案 8 :(得分:1)

将其放入 onResume() 方法中。

binding.etxtSearch.isFocusableInTouchMode = true
binding.etxtSearch.isFocusable = true
binding.etxtSearch.requestFocus() 
val inputMethodManager = context?.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.showSoftInput(binding.etxtSearch, InputMethodManager.SHOW_IMPLICIT)

答案 9 :(得分:0)

第一种方式

    etPassword.post(() -> {
        etPassword.requestFocus();
        InputMethodManager manager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        manager.showSoftInput(etPassword, InputMethodManager.SHOW_IMPLICIT);
    });

第二种方式

在清单中

    <activity
        android:name=".activities.LoginActivity"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="stateVisible"/>

在代码中:

etPassword.requestFocus();

答案 10 :(得分:0)

我尝试了很多方法,但仍无法正常工作,不确定是因为我正在使用从片段到包含编辑文本的活动的共享过渡。

顺便说一下,我的edittext也包裹在LinearLayout中。

我稍微延迟了请求焦点,以下代码对我有用: (科特琳)

 et_search.postDelayed({
     editText.requestFocus()

     showKeyboard()
 },400) //only 400 is working fine, even 300 / 350, the cursor is not showing

showKeyboard()

 val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
 imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)

答案 11 :(得分:0)

我建议使用LifecycleObserverHandling Lifecycles with Lifecycle-Aware Components中的Android Jetpack

我想在出现“片段/活动”时打开和关闭键盘。首先,为EditText定义两个extension functions。您可以将它们放在项目中的任何位置:

fun EditText.showKeyboard() {
    requestFocus()
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}

fun EditText.hideKeyboard() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(this.windowToken, 0)
}

然后定义一个LifecycleObserver,当“活动/片段”到达onResume()onPause时打开和关闭键盘:

class EditTextKeyboardLifecycleObserver(private val editText: WeakReference<EditText>) :
    LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun openKeyboard() {
        editText.get()?.postDelayed({ editText.get()?.showKeyboard() }, 100)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun closeKeyboard() {
        editText.get()?.hideKeyboard()
    }
}

然后将以下行添加到您的任何分片/活动中,您可以随时重复使用LifecycleObserver。例如。片段:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

    // inflate the Fragment layout

    lifecycle.addObserver(EditTextKeyboardLifecycleObserver(WeakReference(myEditText)))

    // do other stuff and return the view

}

答案 12 :(得分:0)

editTxt.setOnFocusChangeListener { v, hasFocus ->
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            if (hasFocus) {
                imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
            } else {
                imm.hideSoftInputFromWindow(v.windowToken, 0)
            }
        }

答案 13 :(得分:0)

我终于找到了一个解决方案并为其创建了一个 Kotlin 类

object KeyboardUtils {

    fun showKeyboard(editText: EditText) {
        editText.requestFocus()
        val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(editText, 0)
    }

    fun hideKeyboard(editText: EditText) {
        val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(editText.windowToken, 0)
    }

}

答案 14 :(得分:-1)

我无法让这些答案自行解决。我的解决方案是将它们结合起来:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
editText.requestFocus();
imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED);

我不确定为什么这对我来说是必要的 - 根据文档,似乎任何一种方法都应该独立运作。