简体   繁体   English

强制打开软键盘

[英]Forcing the Soft Keyboard open

I am trying to force the Soft Keyboard open in an Activity and grab everything that is entered as I want to handle the input myself, I don't have an EditText.我试图在活动中强制打开软键盘并抓取输入的所有内容,因为我想自己处理输入,我没有 EditText。 Currently I have tried this but it does not work.目前我已经尝试过这个,但它不起作用。 I would like the Soft Keyboardto open below mAnswerTextView (Note: it is a TextView not EditText).我希望软键盘在 manswerTextView 下方打开(注意:它是一个 TextView 而不是 EditText)。

    InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    // only will trigger it if no physical keyboard is open
    mgr.showSoftInput(mAnswerTextView, InputMethodManager.SHOW_IMPLICIT);
  1. how do I force the Soft Keyboard open如何强制打开软键盘
  2. How do I gab everything that is entered so that I can handle each character.我如何抓住输入的所有内容,以便我可以处理每个字符。 I would like to flush each character from the Soft Keyboard after I have handled it.我想在处理完软键盘后刷新每个字符。 ie, the user should not be able to enter whole words in the Soft Keyboard.即,用户不应该能够在软键盘中输入整个单词。

try this to force open soft keyboard: 试试这个强制打开软键盘:

((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

then you can to use this code to close the keyboard: 然后你可以使用这段代码来关闭键盘:

((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(_pay_box_helper.getWindowToken(), 0);

You'll probably need to have an editable text area of some kind to take focus. 您可能需要具有某种可编辑的文本区域才能获得焦点。 You can probably have one invisible or on a transparent background with no cursor, though. 但是,您可能有一个不可见或透明背景,没有光标。 You may need to toy around with the focusability settings for the view. 您可能需要使用视图的可聚焦设置。

Use a TextWatcher to check for edits to that EditText with addTextChangedListener , or if you need an even-lower-level hook, set the textview's key listener with its setOnKeyListener() method. 使用TextWatcher检查编辑到的EditText与addTextChangedListener ,或者如果你需要一个甚至下位钩,其setOnKeyListener()方法设置的TextView的主要听众。 See the KeyListener documentation . 请参阅KeyListener文档

Use this call to force the soft keyboard open: 使用此调用强制打开软键盘:

((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE))
    .showSoftInput(myEditText, InputMethodManager.SHOW_FORCED);

and this one to close it: 这个关闭它:

((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE))
    .hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

note that this is really not recommended - forcing the keyboard open is kind of messy. 请注意,这是不推荐的 - 强制打开键盘有点乱。 What's your use case that really necessitates your taking user input without a normal edit box and requires eating user input on a key-by-key basis without echoing it back? 您的用例是什么,真正需要您在没有正常编辑框的情况下接受用户输入,并且需要逐个键地输入用户输入而不回复它?

To force the keyboard to open I used 强制键盘打开我使用过

this.getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);

it worked for me. 它对我有用。

Sometimes the other answers won't work. 有时其他答案不起作用。
Here is another way.. 这是另一种方式..

It will force the keyboard to show when the activity starts by listening to the window focus. 它将通过监听窗口焦点强制键盘显示活动开始的时间。 onWindowFocusChanged() it will clear and request focus of the EditText, then set the soft input mode to visible and set the selection to the text in the box. onWindowFocusChanged()它将清除并请求EditText的焦点,然后将软输入模式设置为visible,并将选择设置为框中的文本。 This should always work if you are calling it from the activity. 如果您从活动中调用它,这应始终有效。

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
        mEditText.clearFocus();
        mEditText.requestFocus();
        getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        mEditText.setSelection(mEditText.getText().toString().length());
    }
}

You may also need 你可能还需要

mEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(mEditText, InputMethodManager.SHOW_IMPLICIT);
            }
        }
    });

Edit: I have also seen the keyboard not open inside nested fragments, beware of those kinds of situations. 编辑:我也看到键盘未在嵌套片段中打开,请注意这些情况。

if you want to control soft keyboard inside activity then use this code: 如果要控制内部活动的软键盘,请使用以下代码:

//create soft keyboard object
InputMethodManager imm = (InputMethodManager)this.getSystemService(INPUT_METHOD_SERVICE);

//1.USE
your_view.setFocusableInTouchMode(true); //Enable touch soft keyboard to this view
//or
your_view.setFocusable(true); //Enable keyboard to this view
imm.showInputMethod(your_view, InputMethodManager.SHOW_IMPLICIT);

//2.USE show keyboard if is hidden or hide if it is shown
imm.toggleSoftInputFromWindow(your_view.getWindowToken(),InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_IMPLICIT_ONLY);
//or
imm.toggleSoftInputFromWindow(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_IMPLICIT_ONLY);

//3.USE (you cannot control imm)
this.getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);

//4.USE (with Dialog)
Dialog d = new Dialog(this, android.R.style.Theme_Panel);
d.getWindow().setTitle(null);
d.setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
d.setOnKeyListener(keyListener);
d.setCanceledOnTouchOutside(true);
d.setCancelable(true);
d.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
d.show();

//to hide keyboard call:
d.dismiss();
//if you want get soft keyboard visibility call:
d.isShowing();

Sadly, as much as I'd have liked to up-vote one of the replies, none worked for me. 可悲的是,尽管我喜欢对其中一个回复进行投票,但没有一个对我有用。 It seems the solution is to wait for the layout phase to complete. 似乎解决方案是等待布局阶段完成。 In the code below, notice how I check if the showKeyboard method returns TRUE, and that's when I remove the global layout listener. 在下面的代码中,请注意我如何检查showKeyboard方法是否返回TRUE,以及当我删除全局布局侦听器时。 Without doing this, it was hit and miss. 没有做到这一点,它被击中和错过。 Now it seems to work perfectly. 现在看起来效果很好。

You need to do the below ideally in onResume() 您需要在onResume()中理想地执行以下操作

@Override
public void onResume()
{
    super.onResume();

    ViewTreeObserver vto = txtTaskTitle.getViewTreeObserver();
            vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
            {
                @Override
                public void onGlobalLayout()
                {
                    if (txtTaskTitle.requestFocus())
                    {
                        if (showKeyboard(getContext(), txtTaskTitle))
                        {
                            txtTaskTitle.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        }
                    }
                }
            });
}

public static boolean showKeyboard(Context context, EditText target)
{
        if (context == null || target == null)
        {
            return false;
        }

        InputMethodManager imm = getInputMethodManager(context);

        ((InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(target, InputMethodManager.SHOW_FORCED);

        boolean didShowKeyboard = imm.showSoftInput(target, InputMethodManager.SHOW_FORCED);
        if (!didShowKeyboard)
        {
            didShowKeyboard = ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(target, InputMethodManager.SHOW_FORCED);
        }
        return didShowKeyboard;
}
if(search.getText().toString().trim().isEmpty()) {
    InputMethodManager imm = (InputMethodManager)getSystemService(
              Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(search.getWindowToken(), 0);
}

I have tested and this is working: 我已经测试过,这是有效的:

... //to show soft keyboard ... //显示软键盘

imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

//to hide it, call the method again //隐藏它,再次调用该方法

imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

Working Great......... 工作得很好.........

edt_searchfilter_searchtext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(hasFocus){
                edt_searchfilter_searchtext.post(new Runnable() {
                    @Override
                    public void run() {
                        InputMethodManager imm = (InputMethodManager) getFragmentActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.showSoftInput(edt_searchfilter_searchtext, InputMethodManager.SHOW_IMPLICIT);
                    }
                });
            }
        }
    });

Below line call when you want to open keyboard 当您要打开键盘时,在线下调用

 edt_searchfilter_searchtext.requestFocus();

Simply, using adding 2 lines will work like a charm: 简单地说,使用添加2行就像魅力一样:

If using XML 如果使用XML

android:focusable="true"
android:focusableInTouchMode="true"

Else in Java: 其他Java:

view.setFocusableInTouchMode(true);
view.requestFocus();

For kotlin user 对于kotlin用户

The whole credit goes to Dmitry's answer 完全归功于德米特里的回答

Open KeyBoard in Fragment . 在Fragment中打开KeyBoard

I have passed mainActivity variable to the fragment constructor as per my requirement, maybe this hack/patch is not recommended as per AndroidGuidLines (well I don`t know). 我已根据我的要求将mainActivity变量传递给fragment constructor ,根据AndroidGuidLines我不建议使用此hack / patch(我不知道)。

But here we go... 但是我们走了......

    @SuppressLint("ValidFragment")
    class MyDemoFragment(private val mainActivity: MainActivity) : Fragment() {

        // EditText declaration
        private lateinit var etMyEditText: EditText

        override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
            val view = inflater.inflate(R.layout.fragment_my_demo, container, false)

            // EditText initialisation
            etMyEditText = view.findViewById(R.id.etMyEditText)
            // This line will open KeyBoard
            (mainActivity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
            // Requesting cursor focus   
            etMyEditText.requestFocus()

            return view
        }
    }

You can use this KeyboardHelper.java class 您可以使用此KeyboardHelper.java类

    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 || view == null) {
                return;
            }

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

        }


        public static void hideSoftKeyboardForced(Context context, View view) {
            if (context == null) {


  return;
        }

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

    }

    public static void hideSoftKeyboard(Context context, EditText editText) {
        if (context == null) {
            return;
        }
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(editText.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

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

        if (context == null) {
            return;
        }

        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
        editText.requestFocus();
    }

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

        if (context == null) {
            return;
        }

        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
        editText.requestFocus();
    }




}

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

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