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

后端 未结 15 1241
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();
              } 
           }
         );
       }
    }
    

提交回复
热议问题