Method to get all EditTexts in a View

后端 未结 5 697
无人共我
无人共我 2020-11-30 07:58

can anyone help me with coding a method to get all EditTexts in a view? I would like to implement the solution htafoya posted here: How to hide soft keyboard on android afte

5条回答
  •  孤城傲影
    2020-11-30 08:05

    EDIT

    MByD pointed me to an error, thus making my answer almost identical to that of blackbelt. I have edited mine to the correct approach.


    You could do a for-each loop and then check if each view is of the type EditText:

    ArrayList myEditTextList = new ArrayList();
    
    for( int i = 0; i < myLayout.getChildCount(); i++ )
      if( myLayout.getChildAt( i ) instanceof EditText )
        myEditTextList.add( (EditText) myLayout.getChildAt( i ) );
    

    You could also, instead of having a list of EditTexts, have a list of ID's and then just add the id of the child to the list: myIdList.add( child.getId() );


    To access your layout you need to get a reference for it. This means you need to provide an ID for your layout in your XML:

    
       //Here is where your EditTexts would be declared
    
    

    Then when you inflate the layout in your activity you just make sure to save a reference to it:

    LinearLayout myLinearLayout;
    
    public void onCreate( Bundle savedInstanceState ) {
       super( savedInstanceState );
       setContentView( R.layout.myLayoutWithEditTexts );
    
       ...
    
       myLinearLayout = (LinearLayout) findViewById( R.id.myLinearLayout );
    }
    

    You then have a reference to your the holder of your EditTexts within the activity.

提交回复
热议问题