简体   繁体   English

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

[英]How can I set the focus (and display the keyboard) on my EditText programmatically

I have a layout which contains some views like this:我有一个布局,其中包含一些这样的视图:

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

How can I set the focus (display the keyboard) on my EditText programmatically?如何以编程方式在我的EditText上设置焦点(显示键盘)?

I've tried this and it works only when I launch my Activity normally, but when I launch it in a TabHost , it doesn't work.我试过这个,它只在我正常启动我的Activity时有效,但是当我在TabHost中启动它时,它不起作用。

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

Try this:试试这个:

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() http://developer.android.com/reference/android/view/View.html#requestFocus()

use:采用:

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

This worked for me, Thanks to ungalcrys这对我有用,感谢ungalcrys

Show keyboard:显示键盘:

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

Hide keyboard:隐藏键盘:

InputMethodManager imm = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
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);

showSoftInput was not working for me at all. showSoftInput根本不适合我。

I figured I needed to set the input mode : android:windowSoftInputMode="stateVisible" (here in the Activity component in the manifest)我想我需要设置输入模式: android:windowSoftInputMode="stateVisible" (在清单的 Activity 组件中)

Hope this help!希望这有帮助!

Here is how a kotlin extension for showing and hiding the soft keyboard can be made:以下是如何制作用于显示和隐藏软键盘的 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)
}

Then you can just do this:然后你可以这样做:

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

Here is KeyboardHelper Class for hiding and showing keyboard这是用于隐藏和显示键盘的 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(final Context context, final View view) {
    if (context == null) {
        return;
    }
    view.requestFocus();
    view.postDelayed(new Runnable() {
        @Override
        public void run() {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}, 1000);
}

public static void hideSoftKeyboard(final Context context, final EditText editText) {
    editText.requestFocus();
    editText.postDelayed(new Runnable() {
        @Override
        public void run() {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
}, 1000);
}


public static void openSoftKeyboard(final Context context, final EditText editText) {
    editText.requestFocus();
    editText.postDelayed(new Runnable() {
        @Override
        public void run() {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
}
}, 1000);
}
}

I recommend using a LifecycleObserver which is part of the Handling Lifecycles with Lifecycle-Aware Components of Android Jetpack .我建议使用LifecycleObserver ,它是处理生命周期与Android Jetpack 的生命周期感知组件的一部分。

I want to open and close the Keyboard when the Fragment/Activity appears.我想在片段/活动出现时打开和关闭键盘。 Firstly, define two extension functions for the EditText.首先,为 EditText 定义两个扩展函数 You can put them anywhere in your project:您可以将它们放在项目中的任何位置:

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

Then define a LifecycleObserver which opens and closes the keyboard when the Activity/Fragment reaches onResume() or onPause :然后定义一个 LifecycleObserver,它在 Activity/Fragment 到达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()
    }
}

Then add the following line to any of your Fragments/Activities, you can reuse the LifecycleObserver any times.然后将以下行添加到您的任何片段/活动中,您可以随时重用 LifecycleObserver。 Eg for a Fragment:例如对于片段:

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

}

I tried a lot ways and it's not working tho, not sure is it because i'm using shared transition from fragment to activity containing the edit text.我尝试了很多方法,但它不起作用,不确定是不是因为我正在使用从片段到包含编辑文本的活动的共享转换。

Btw my edittext is also wrapped in LinearLayout.顺便说一句,我的 edittext 也包含在 LinearLayout 中。

I added a slight delay to request focus and below code worked for me: (Kotlin)我添加了一个轻微的延迟来请求焦点,下面的代码对我有用:(Kotlin)

 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)

Put this into onResume() method.将其放入 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)

I know this is a late reply, but for people who are like me looking to do this in 2022, to find out that toggleSoftInput is deprecated (as of level 31), here is the new approach using showSoftInput:我知道这是一个迟到的回复,但对于像我一样希望在 2022 年这样做的人,要发现 toggleSoftInput 已被弃用(从第 31 级开始),这是使用 showSoftInput 的新方法:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
editView.requestFocus();
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
                        .showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);

I tried the toggleSoftInput but found some issues, like the keyboard stays when I press the home button,but this approach worked for me perfectly.我尝试了 toggleSoftInput 但发现了一些问题,比如当我按下主页按钮时键盘停留,但这种方法对我来说非常有效。

First way :第一种方式

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

Second way :第二种方式

In Manifest:在清单中:

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

In code:在代码中:

etPassword.requestFocus();
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)
            }
        }

I tried the top answer by David Merriman and it also didn't work in my case.我尝试了 David Merriman 的最佳答案,但在我的情况下也不起作用。 But I found the suggestion to run this code delayed here and it works like a charm.但是我发现运行这段代码的建议在这里延迟,它的作用就像一个魅力。

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)

I finally figured out a solution and create a Kotlin class for it我终于找到了一个解决方案并为它创建了一个 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)
    }

}

In "OnCreate" move the cursor to the input field, but the keyboard will not open:在“OnCreate”中将 cursor 移动到输入字段,但键盘不会打开:

window().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
)
editText.requestFocus()

After that, while the user enters the text:之后,当用户输入文本时:

val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
window.setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE
)
imm.showSoftInput(editText, 0)

will work adequately and the keyboard will open when needed without setting time delays.将充分工作,键盘将在需要时打开,无需设置时间延迟。 Remember, after entering the text, you must:请记住,输入文本后,您必须:

window.setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
)
requestFocus()

I did it only in one line of code我只用一行代码做到了

firstInputField.setNextFocusDownId(R.id.id_of_next_targeted_text_field);

I'm Using this code for show keyboard programmatically.我正在使用此代码以编程方式显示键盘。

binding!!.etAssignToName.postDelayed( {
                mActivity.runOnUiThread {
                    showKeyboard(binding!!.etAssignToName,mContext)
                }
            },300)

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

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

I couldn't get any of these answers to work on their own.我无法获得这些答案中的任何一个来独立工作。 The solution for me was to combine them:我的解决方案是将它们结合起来:

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

I'm not sure why that was required for me -- according to the docs it seems that either method should have worked on their own.我不确定为什么我需要这样做——根据文档,这两种方法似乎都应该独立工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM