按照廣大熱心網友的指導,做了以下操作:
ditText.setFocusable(true);
editText.setFocusableInTouchMode(true);
editText.requestFocus();
activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
以及在AndroidManifest.xml中設置:
android:windowSoftInputMode="stateVisible|adjustResize"
然鵝,發現並無卵用。後來看到個覺得靠譜的解釋:
Android加載刷新UI的時候,是從左到右,從上到下的順序,正在加載的過程中,如果此時requestFocus(),的話,有可能此時還沒把整個界面刷新好,導致requestFocus無效。
因此,做了個延遲加載:
editText.postDelayed(() -> {
editText.setFocusable(true);
editText.setFocusableInTouchMode(true);
editText.requestFocus();
}, 300);
果然就可以了,看到光標開始在閃了,可是此時如果想讓他自動彈出來呢?
直接貼上完整代碼吧,延時時間自定:
/**
* EditText獲取焦點並顯示軟鍵盤
*/
public static void showSoftInputFromWindow(Activity activity, EditText editText) {
editText.postDelayed(() -> {
editText.setFocusable(true);
editText.setFocusableInTouchMode(true);
editText.requestFocus();
editText.setSelection(editText.getText().toString().length()); //移動光標到最後
}, 300);
// 強制打開鍵盤
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
InputMethodManager inputMethodManager =
(InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}
}, 200);
}