简体   繁体   English

以编程方式打开软键盘

[英]Open soft keyboard programmatically

I have an activity with no child widgets for it and the corresponding xml file is,我有一个没有子部件的活动,相应的 xml 文件是,

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myLayout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:focusable="true"
>
</LinearLayout>

and I want to open soft keyboard programmatically while the activity gets start.and what I've tried upto now is,我想在活动开始时以编程方式打开软键盘。我现在尝试的是,

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    if (inputMethodManager != null) {
        inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    }

Give me some guidance.给我一些指导。

I have used the following lines to display the soft keyboard manually inside the onclick event, and the keyboard is visible.我已经使用以下几行在 onclick 事件中手动显示软键盘,并且键盘是可见的。

InputMethodManager inputMethodManager =
    (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInputFromWindow(
    linearLayout.getApplicationWindowToken(),
    InputMethodManager.SHOW_FORCED, 0);

But I'm still not able to open this while the activity gets opened, so are there any solution for this?但是在活动打开时我仍然无法打开它,那么有什么解决方案吗?

In your manifest file, try adding the following to the <activity> that you want to show the keyboard when the activity starts:在您的清单文件中,尝试将以下内容添加到您希望在活动开始时显示键盘的<activity>中:

android:windowSoftInputMode="stateVisible"

This should cause the keyboard to become visible when the activity starts.这应该会导致键盘在活动开始时变得可见。

For more options, checkout the documentation .有关更多选项,请查看文档

Please follow the below code.请按照下面的代码。 I am sure your problem will be solved.我相信你的问题会得到解决。

if (imm != null){
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
   } 

This is works这是作品

<activity
    ...
    android:windowSoftInputMode="stateVisible" >
</activity>

or或者

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

All I needed was to expose the keyboard, in a very precise moment.我所需要的只是在一个非常精确的时刻露出键盘。 This worked for me!这对我有用! Thanks Benites.谢谢贝尼特。

    private Handler mHandler= new Handler();

And in the very precise moment:在非常精确的时刻:

    mHandler.post(
    new Runnable() {
        public void run() {
            InputMethodManager inputMethodManager =  (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
            inputMethodManager.toggleSoftInputFromWindow(yourEditText.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);
            yourEditText.requestFocus();
        }
    }); 

I have used the following lines to display the soft keyboard manually inside the onclick event.我使用以下几行在 onclick 事件中手动显示软键盘。

public void showKeyboard(final EmojiconEditText ettext){
          ettext.requestFocus();
          ettext.postDelayed(new Runnable(){
            @Override public void run(){
              InputMethodManager keyboard=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
              keyboard.showSoftInput(ettext,0);
            }
          }
        ,200);
        }

Kotlin科特林

fun hideKeyboard(activity: Activity) {
    val view = activity.currentFocus
    val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(view != null)
    methodManager.hideSoftInputFromWindow(view!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}

private fun showKeyboard(activity: Activity) {
    val view = activity.currentFocus
    val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(view != null)
    methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}

Java爪哇

public static void hideKeyboard(Activity activity) {
    View view = activity.getCurrentFocus();
    InputMethodManager methodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    assert methodManager != null && view != null;
    methodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}

private static void showKeyboard(Activity activity) {
    View view = activity.getCurrentFocus();
    InputMethodManager methodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    assert methodManager != null && view != null;
    methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}

Put that in onResume method:把它放在 onResume 方法中:

findViewById(R.id.root_view_of_your_activity_layout).post(
new Runnable() {
    public void run() {
        InputMethodManager inputMethodManager =  (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
        inputMethodManager.toggleSoftInputFromWindow(yourEditText.getApplicationWindowToken(),     InputMethodManager.SHOW_FORCED, 0);
        yourEditText.requestFocus();
    }
});

the runnable is needed because when the OS fires the onResume method you can't be sure that all the views where draw, so the post method called from your root layout makes it wait till every view is ready. runnable 是必需的,因为当操作系统触发 onResume 方法时,您无法确定所有视图都在哪里绘制,因此从您的根布局调用的 post 方法使其等待每个视图都准备好。

in onCreate method of activity or onActivityCreated of a fragment在活动的onCreate方法或片段的onActivityCreated

....
view.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        @Override
        public boolean onPreDraw() {
            view.removeOnPreDrawListener(this);
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

            // !Pay attention to return `true`
            // Chet Haase told to 
            return true;
        }
    });

seems like this is working好像这行得通

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patientid);

        editText = (EditText)findViewById(R.id.selectPatient);
        //editText.requestFocus(); //works without that

    }

@Override
    protected void onResume() {

        findViewById(R.id.selectPatient).postDelayed(
        new Runnable() {
            public void run() {
                 editText.requestFocus();
                InputMethodManager inputMethodManager =  (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.showSoftInput(editText,InputMethodManager.SHOW_IMPLICIT);
            }
        },100);
        super.onResume();
    }

seems this works better: in manifest:似乎这效果更好:在清单中:

<application>
    <activity
        android:name="com.doodkin.myapp.ReportActivity"
        android:label="@string/title_activity_report"
        android:screenOrientation="sensor" 
        android:windowSoftInputMode="stateHidden" > // add this or stateVisible
    </activity>
</application>

seems the manifest working in android 4.2.2 but not working in android 4.0.3似乎清单在 android 4.2.2 中工作但在 android 4.0.3 中不工作

I used it as singleton like:我将它用作单身人士,例如:

public static void showSoftKeyboard(final Context context, final EditText editText) {
        try {
            editText.requestFocus();
            editText.postDelayed(
                    new Runnable() {
                        @Override
                        public void run() {
                            InputMethodManager keyboard = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                            keyboard.showSoftInput(editText, 0);
                        }
                    }
                    , 200);
        } catch (NullPointerException npe) {
            npe.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Use it in your activity like:在您的活动中使用它,例如:

showSoftKeyboard(this, yourEditTextToFocus);

I have used like this to show the soft keyboard programatically and this is worked for me to prevent the auto resize of the screen while launching the keyboard.我用这样的方式以编程方式显示软键盘,这对我来说可以防止在启动键盘时自动调整屏幕大小。

In manifest:在清单中:

<activity android:name="XXXActivity" android:windowSoftInputMode="adjustPan">
</activity>

In XXXActvity:在 XXX 活动中:

EditText et =  (EditText))findViewById(R.id.edit_text);  
  Timer timer = new Timer();
            TimerTask task = new TimerTask() {

                @Override
                public void run() {
                    InputMethodManager inputMethodManager=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.toggleSoftInputFromWindow(et.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);

                }
            };
            timer.schedule(task, 200);

I assume this will save others time to search for this problem.我认为这将节省其他人搜索此问题的时间。

InputMethodManager inputMethodManager=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);

This works:这有效:

private static void showKeyboard(Activity activity) {
    View view = activity.getCurrentFocus();
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}

And you call this method like this:你这样调用这个方法:

showKeyboard(NameOfActivity.this);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

在 onResume() 中使用上述代码打开软键盘

InputMethodManager.SHOW_FORCED isn't good choice. InputMethodManager.SHOW_FORCED 不是好的选择。 If you use this setting you should manage hiding keyboard state.如果您使用此设置,您应该管理隐藏键盘状态。 My suggestion is like this;我的建议是这样的;

    public void showSoftKeyboard(View view) {
    InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
    view.requestFocus();
    inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
}

Also, you can focus on view (usually EditText) taking parameters it.此外,您可以专注于获取参数的视图(通常是 EditText)。 This makes it a more useful function这使它成为一个更有用的功能

for more info about InputMethodManager.SHOW_IMPLICIT and SHOW_FORCED;有关 InputMethodManager.SHOW_IMPLICIT 和 SHOW_FORCED 的更多信息; InputMethodManager 输入法管理器

public final class AAUtilKeyboard {

public static void openKeyboard(final Activity activity, final EditText editText) {
    final InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    if (imm != null) {
        imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
    }
}

public static void hideKeyboard(final Activity activity) {
    final View view = activity.getCurrentFocus();
    if (view != null) {
        final InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
}

perfectly working code to show and hide softkeyboard for edittextbox.....完美的工作代码来显示和隐藏edittextbox的软键盘.....

// code to hide soft keyboard
public void hideSoftKeyBoard(EditText editBox) {
     InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);  
     imm.hideSoftInputFromWindow(editBox.getWindowToken(), 0);  
}




// code to show soft keyboard
private void showSoftKeyBoard(EditText editBox){
     InputMethodManager inputMethodManager = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
     editBox.requestFocus();
     inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}

Based on above answers like this it works in KOTLIN as long as you have the context.基于上述这样的答案,只要您有上下文,它就可以在KOTLIN中使用。

fun Context.showKeyboard(editText: EditText) {

    editText.requestFocus()
    editText.setSelection(editText.text.length)

    GlobalScope.launch {
        delay(200L)

        val inputMethodManager: InputMethodManager =
            getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.toggleSoftInputFromWindow(
            editText.applicationWindowToken,
            InputMethodManager.SHOW_IMPLICIT, 0
        )
    }
}

Then you can call it in your fragment for example as follows然后你可以在你的片段中调用它,例如如下

requireContext().showKeyboard(binding.myEditText) requireContext().showKeyboard(binding.myEditText)

import androidx.core.view.WindowInsetsCompat.Type
import androidx.core.view.WindowInsetsControllerCompat

fun Activity.openKeyboard() {
    WindowInsetsControllerCompat(window, window.decorView).show(Type.ime())
}

fun Activity.hideKeyboard() {
    WindowInsetsControllerCompat(window, window.decorView).hide(Type.ime())
}

Similar to the answer of @ShimonDoodkin this is what I did in a fragment.类似于@ShimonDoodkin 的答案,这是我在片段中所做的。

https://stackoverflow.com/a/29229865/2413303 https://stackoverflow.com/a/29229865/2413303

    passwordInput.postDelayed(new ShowKeyboard(), 300); //250 sometimes doesn't run if returning from LockScreen

Where ShowKeyboard is ShowKeyboard在哪里

private class ShowKeyboard implements Runnable {
    @Override
    public void run() {
        passwordInput.setFocusableInTouchMode(true);
        passwordInput.requestFocus();            
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(passwordInput, 0);
    }
}

After a successful input, I also make sure I hide the keyboard成功输入后,我还要确保隐藏键盘

getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(getView().getWindowToken(), 0);

This is the required source code :这是所需的源代码:

public static void openKeypad(final Context context, final View v) 
 {
new Handler().postDelayed(new Runnable() 
{
    @Override
    public void run() 
    {
        InputMethodManager inputManager =   (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE); 
        inputManager.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);    
        Log.e("openKeypad", "Inside Handler");
    }
},300);}

For details , Please go through this link.有关详细信息,请通过此链接。 This helped me.这对我有帮助。 https://github.com/Nikhillosalka/Keyboard/blob/master/README.md https://github.com/Nikhillosalka/Keyboard/blob/master/README.md

There are already too many answers but nothing worked for me apart from this已经有太多答案了,但除此之外没有什么对我有用

inputMethodManager.showSoftInput(emailET,InputMethodManager.SHOW_FORCED);

I used showSoftInput with SHOW_FORCED我将showSoftInputSHOW_FORCED一起使用

And my activity has我的活动有

 android:windowSoftInputMode="stateVisible|adjustResize"

hope this helps someone希望这可以帮助某人

Post this method in your base activity and use it other activities like a charm将此方法发布到您的基础活动中,并将其用于其他活动,例如魅力

public void openKeyboard() {
    InputMethodManager imm =
            (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    if (imm != null) {
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    }
}

I like to do it as an extension to Context so you can call it anywhere我喜欢把它作为 Context 的扩展,所以你可以在任何地方调用它

fun Context.showKeyboard(editText: EditText) {
    val inputMethodManager: InputMethodManager =
        getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    inputMethodManager.toggleSoftInputFromWindow(
        editText.applicationWindowToken,
        InputMethodManager.SHOW_IMPLICIT, 0
    )
    editText.requestFocus()
    editText.setSelection(editText.text.length)
}

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

If you want the keyboard to be up along with the activity/fragment launch, you can use the below code.如果您希望键盘与活动/片段启动一起启动,您可以使用以下代码。

new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager inputMethodManager =
                        (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.toggleSoftInputFromWindow(
                        etPhoneNumber.getApplicationWindowToken(),
                        InputMethodManager.SHOW_FORCED, 0);
            }
        }, 500);

In the Kotlin , you can use the below extension functions to show and hide the soft keyboard.Kotlin中,您可以使用以下扩展功能来显示和隐藏软键盘。

/**
  * Extension method to provide show keyboard for [Activity].
 */
fun Activity.showSoftKeyboard() {
  if (currentFocus != null) {
    val inputMethodManager =
        getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
 inputMethodManager.showSoftInput(this.currentFocus,InputMethodManager.SHOW_IMPLICIT)
   } 
}


/**
 * Extension method to provide hide keyboard for [Activity].
 */
fun Activity.hideSoftKeyboard() {
   if (currentFocus != null) {
      val inputMethodManager =
        getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    inputMethodManager.hideSoftInputFromWindow(currentFocus!!.windowToken, 0)
    }
 }

That's all!就这样! Cheers!干杯!

Best way to open forced Keyboard is call below kotlin code code:-打开强制键盘的最佳方法是在 kotlin 代码代码下方调用:-

 val inputMethodManager: InputMethodManager =
            getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager

        inputMethodManager.showSoftInput(
            editText, 2)

Try use this:尝试使用这个:

    fun closeKeyboard(view: View) {
    (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
        .hideSoftInputFromWindow(view.windowToken, HIDE_IMPLICIT_ONLY)
}

fun showKeyBoard(view: View) {
    (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).showSoftInput(
        view,
        SHOW_IMPLICIT
    )
}

And if not work, try wrap func in a run block like this:如果不起作用,请尝试将 func 包装在这样的运行块中:

  view.postDelayed({showKeyBoard(view)},100)

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

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