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

后端 未结 15 1074
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:29

    You should add this:

    android:focusableInTouchMode="true"
    
    0 讨论(0)
  • 2020-12-02 15:29

    Try

    comp.requestFocusInWindow();
    
    0 讨论(0)
  • 2020-12-02 15:31

    None of the answers above works for me. The only (let's say) solution has been to change the first TextView in a disabled EditText that receives focus and then add

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

    in the onCreate callback to prevent keyboard to be shown. Now my first EditText looks like a TextView but can get the initial focus, finally.

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

    Set these lines to OnResume as well and make sure if focusableInTouch is set to true while you initialize your controls

    <controlName>.requestFocus();
    
    <controlName>.requestFocusFromTouch();
    
    0 讨论(0)
  • 2020-12-02 15:33

    You can try just hidding the keyboard. Something like this:

    InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    
    0 讨论(0)
  • 2020-12-02 15:34

    to change the focus make the textView in xml focusable

    <TextView
                **android:focusable="true"**
                android:id="@+id/tv_id"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
    

    and in java in on create

    textView.requestFocus();

    or simply hide the keyboard

    public void hideKeyBoard(Activity act) {
        act.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        InputMethodManager imm = (InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE);
    }
    
    0 讨论(0)
提交回复
热议问题