簡體   English   中英

以編程方式打開軟鍵盤

[英]Open soft keyboard programmatically

我有一個沒有子部件的活動,相應的 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>

我想在活動開始時以編程方式打開軟鍵盤。我現在嘗試的是,

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

給我一些指導。

我已經使用以下幾行在 onclick 事件中手動顯示軟鍵盤,並且鍵盤是可見的。

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

但是在活動打開時我仍然無法打開它,那么有什么解決方案嗎?

在您的清單文件中,嘗試將以下內容添加到您希望在活動開始時顯示鍵盤的<activity>中:

android:windowSoftInputMode="stateVisible"

這應該會導致鍵盤在活動開始時變得可見。

有關更多選項,請查看文檔

請按照下面的代碼。 我相信你的問題會得到解決。

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

這是作品

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

或者

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

我所需要的只是在一個非常精確的時刻露出鍵盤。 這對我有用! 謝謝貝尼特。

    private Handler mHandler= new Handler();

在非常精確的時刻:

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

我使用以下幾行在 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);
        }

科特林

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

爪哇

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

把它放在 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();
    }
});

runnable 是必需的,因為當操作系統觸發 onResume 方法時,您無法確定所有視圖都在哪里繪制,因此從您的根布局調用的 post 方法使其等待每個視圖都准備好。

在活動的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;
        }
    });

好像這行得通

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

似乎這效果更好:在清單中:

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

似乎清單在 android 4.2.2 中工作但在 android 4.0.3 中不工作

我將它用作單身人士,例如:

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

在您的活動中使用它,例如:

showSoftKeyboard(this, yourEditTextToFocus);

我用這樣的方式以編程方式顯示軟鍵盤,這對我來說可以防止在啟動鍵盤時自動調整屏幕大小。

在清單中:

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

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

我認為這將節省其他人搜索此問題的時間。

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

這有效:

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

你這樣調用這個方法:

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

在 onResume() 中使用上述代碼打開軟鍵盤

InputMethodManager.SHOW_FORCED 不是好的選擇。 如果您使用此設置,您應該管理隱藏鍵盤狀態。 我的建議是這樣的;

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

此外,您可以專注於獲取參數的視圖(通常是 EditText)。 這使它成為一個更有用的功能

有關 InputMethodManager.SHOW_IMPLICIT 和 SHOW_FORCED 的更多信息; 輸入法管理器

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

完美的工作代碼來顯示和隱藏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);
}

基於上述這樣的答案,只要您有上下文,它就可以在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
        )
    }
}

然后你可以在你的片段中調用它,例如如下

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

類似於@ShimonDoodkin 的答案,這是我在片段中所做的。

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

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

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

成功輸入后,我還要確保隱藏鍵盤

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

這是所需的源代碼:

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

有關詳細信息,請通過此鏈接。 這對我有幫助。 https://github.com/Nikhillosalka/Keyboard/blob/master/README.md

已經有太多答案了,但除此之外沒有什么對我有用

inputMethodManager.showSoftInput(emailET,InputMethodManager.SHOW_FORCED);

我將showSoftInputSHOW_FORCED一起使用

我的活動有

 android:windowSoftInputMode="stateVisible|adjustResize"

希望這可以幫助某人

將此方法發布到您的基礎活動中,並將其用於其他活動,例如魅力

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

我喜歡把它作為 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)
}

如果您希望鍵盤與活動/片段啟動一起啟動,您可以使用以下代碼。

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

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

就這樣! 干杯!

打開強制鍵盤的最佳方法是在 kotlin 代碼代碼下方調用:-

 val inputMethodManager: InputMethodManager =
            getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager

        inputMethodManager.showSoftInput(
            editText, 2)

嘗試使用這個:

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

如果不起作用,請嘗試將 func 包裝在這樣的運行塊中:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM