EditText request focus not working

后端 未结 11 602
自闭症患者
自闭症患者 2020-12-15 17:03

I have an EditText and a Button. On click of the button i want to open the EditText keyboard and at the same time request focus on the

相关标签:
11条回答
  • 2020-12-15 17:21

    The above solutions will work if the EditText is enabled.

    In my code, I have disabled the view at one point and trying to request focus later without enabling. If none of the above worked, enable the EditText and then proceed with the above solutions.

    In my case it is like,

     etpalletId.isEnabled = true
     etpalletId.text!!.clear()
     etpalletId.requestFocus()
     etpalletId.isCursorVisible = true
    
    0 讨论(0)
  • 2020-12-15 17:23

    Minimalist Kotlin extension version because we should pretend these sorts of obtuse calls into system services are not necessary:

    fun EditText.requestKeyboardFocus() {
        val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
    }
    
    0 讨论(0)
  • 2020-12-15 17:26

    Following saleh sereshki's answer and pauminku's comment, I'm using:

    m_SearchEditText.post(new Runnable() {
                @Override
                public void run() {
                    m_SearchEditText.requestFocus();
                }
            });
    

    which in Kotlin is the equivalent to:

    m_SearchEditText.post { m_SearchEditText.requestFocus() }
    
    0 讨论(0)
  • 2020-12-15 17:33

    ensure that the edittext is focusable in touch mode. You can do it two way.

    In xml:

    android:focusableInTouchMode="true"
    

    in Java:

    view.setFocusableInTouchMode(true);
    

    Personally I don't trust the XML definition of this param. I always request focus by these two lines of code:

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

    The keyboard shoul appear on itself without the need to call InputMethodManager.

    It works in most of the cases. Once it did not work for me because I have lost the reference to the object due to quite heavy processing - ensure that this is not your issue.

    0 讨论(0)
  • 2020-12-15 17:38

    I was combining some answers and found the following solution:

    fun Fragment.focusEditText(editText: EditText) {
    Timer("Timer", false).schedule(50) {
        requireActivity().runOnUiThread(java.lang.Runnable {
            editText.isFocusableInTouchMode = true
            editText.requestFocus()
            val manager =
                requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            manager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
        })
    }
    

    The timer delay makes sure that the focus request is working and the keyboard is opened manually because it did not work implicitely for me.

    0 讨论(0)
提交回复
热议问题