How to set focus on a view when a layout is created and displayed?

后端 未结 15 1075
Happy的楠姐
Happy的楠姐 2020-12-02 15:07

Currently, I have a layout which contains a Button, a TextView and an EditText. When the layout is displayed, the focus will be automa

相关标签:
15条回答
  • 2020-12-02 15:54

    Set focus: The framework will handled moving focus in response to user input. To force focus to a specific view, call requestFocus()

    0 讨论(0)
  • 2020-12-02 15:54

    The last suggestion is the correct solution. Just to repeat, first set android:focusable="true" in the layout xml file, then requestFocus() on the view in your code.

    0 讨论(0)
  • 2020-12-02 15:55

    Focus is for selecting UI components when you are using something besides touch (ie, a d-pad, a keyboard, etc.). Any view can receive focus, though some are not focusable by default. (You can make a view focusable with setFocusable(true) and force it to be focused with requestFocus().)

    However, it is important to note that when you are in touch mode, focus is disabled. So if you are using your fingers, changing the focus programmatically doesn't do anything. The exception to this is for views that receive input from an input editor. An EditText is such an example. For this special situation setFocusableInTouchMode(true) is used to let the soft keyboard know where to send input. An EditText has this setting by default. The soft keyboard will automatically pop up.

    If you don't want the soft keyboard popping up automatically then you can temporarily suppress it as @abeljus noted:

    InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    

    When a user clicks on the EditText, it should still show the keyboard, though.

    Further reading:

    • Having Trouble Focusing? A Primer on Focus in Android
    • Android Developers Blog: Touch Mode
    0 讨论(0)
提交回复
热议问题