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

后端 未结 15 1076
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:36

    To set focus, delay the requestFocus() using a Handler.

    private Handler mHandler= new Handler();
    
    public class HelloAndroid extends Activity {
       /** Called when the activity is first created. */
       @Override
       public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
    
         LinearLayout mainVw = (LinearLayout) findViewById(R.id.main_layout);
    
         LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( 
               LinearLayout.LayoutParams.FILL_PARENT,
               LinearLayout.LayoutParams.WRAP_CONTENT);
    
         EditText edit = new EditText(this);
         edit.setLayoutParams(params);
         mainVw.addView(edit);
    
         TextView titleTv = new TextView(this);
         titleTv.setText("test");
         titleTv.setLayoutParams(params);
         mainVw.addView(titleTv);
    
         mHandler.post(
           new Runnable() 
           {
              public void run() 
              {
                titleTv.requestFocus();
              } 
           }
         );
       }
    }
    
    0 讨论(0)
  • 2020-12-02 15:38

    You can start by adding android:windowSoftInputMode to your activity in AndroidManifest.xml file.

    <activity android:name="YourActivity"
              android:windowSoftInputMode="stateHidden" />
    

    This will make the keyboard to not show, but EditText is still got focus. To solve that, you can set android:focusableInTouchmode and android:focusable to true on your root view.

    <LinearLayout android:orientation="vertical"
                  android:focusable="true"
                  android:focusableInTouchMode="true"
                  ...
                  >
        <EditText
             ...
           />
        <TextView
             ...
           />
        <Button
             ...
           />
    </LinearLayout>
    

    The code above will make sure that RelativeLayout is getting focus instead of EditText

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

    you can add an edit text of size "0 dip" as the first control in ur xml, so, that will get the focus on render.(make sure its focusable and all...)

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

    i think a text view is not focusable. Try to set the focus on a button for example, or to set the property focusable to true.

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

    Set

     android:focusable="true"
    

    in your <EditText/>

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

    This works:

    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    
    0 讨论(0)
提交回复
热议问题