簡體   English   中英

如何以編程方式在我的 EditText 上設置焦點(並顯示鍵盤)

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

我有一個布局,其中包含一些這樣的視圖:

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

如何以編程方式在我的EditText上設置焦點(顯示鍵盤)?

我試過這個,它只在我正常啟動我的Activity時有效,但是當我在TabHost中啟動它時,它不起作用。

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

試試這個:

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

采用:

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

這對我有用,感謝ungalcrys

顯示鍵盤:

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

隱藏鍵盤:

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根本不適合我。

我想我需要設置輸入模式: android:windowSoftInputMode="stateVisible" (在清單的 Activity 組件中)

希望這有幫助!

以下是如何制作用於顯示和隱藏軟鍵盤的 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)
}

然后你可以這樣做:

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

這是用於隱藏和顯示鍵盤的 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);
}
}

我建議使用LifecycleObserver ,它是處理生命周期與Android Jetpack 的生命周期感知組件的一部分。

我想在片段/活動出現時打開和關閉鍵盤。 首先,為 EditText 定義兩個擴展函數 您可以將它們放在項目中的任何位置:

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

然后定義一個 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()
    }
}

然后將以下行添加到您的任何片段/活動中,您可以隨時重用 LifecycleObserver。 例如對於片段:

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

}

我嘗試了很多方法,但它不起作用,不確定是不是因為我正在使用從片段到包含編輯文本的活動的共享轉換。

順便說一句,我的 edittext 也包含在 LinearLayout 中。

我添加了一個輕微的延遲來請求焦點,下面的代碼對我有用:(Kotlin)

 et_search.postDelayed({
     editText.requestFocus()

     showKeyboard()
 },400) //only 400 is working fine, even 300 / 350, the cursor is not showing

顯示鍵盤()

 val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
 imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)

將其放入 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)

我知道這是一個遲到的回復,但對於像我一樣希望在 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);

我嘗試了 toggleSoftInput 但發現了一些問題,比如當我按下主頁按鈕時鍵盤停留,但這種方法對我來說非常有效。

第一種方式

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

第二種方式

在清單中:

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

在代碼中:

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

我嘗試了 David Merriman 的最佳答案,但在我的情況下也不起作用。 但是我發現運行這段代碼的建議在這里延遲,它的作用就像一個魅力。

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)

我終於找到了一個解決方案並為它創建了一個 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)
    }

}

在“OnCreate”中將 cursor 移動到輸入字段,但鍵盤不會打開:

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

之后,當用戶輸入文本時:

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

將充分工作,鍵盤將在需要時打開,無需設置時間延遲。 請記住,輸入文本后,您必須:

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

我只用一行代碼做到了

firstInputField.setNextFocusDownId(R.id.id_of_next_targeted_text_field);

我正在使用此代碼以編程方式顯示鍵盤。

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

我無法獲得這些答案中的任何一個來獨立工作。 我的解決方案是將它們結合起來:

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

我不確定為什么我需要這樣做——根據文檔,這兩種方法似乎都應該獨立工作。

暫無
暫無

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

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