Android Development: How To Get All EditText Child

2019-05-24 13:45发布

问题:

Basically, I have a LinearLayout that holds a random amount of horizontal LinearLayouts, and in each of the horizontal LinearLayouts there's a TextView and an EditText. I want to be able to get the value of each EditText children of the master LinearLayout.

Sorry if it's confusing, I'm no good at explaining things!

Could I just set the same ID for each of the EditTexts then use findViewById, or would that only return the first instance of an EditText?

Thanks, Alex.

回答1:

You would need to call findViewById on each of the LinearLayouts. If you do this, you can set the same ID for each EditText.



回答2:

 LinearLayout ll = //Your Layout this can be any Linear or Relative layout 
                     //in which you added your spinners at runtime ;

    int count = ll.getChildCount();
    for(int i =0;i<count;i++)
    {
        View v = ll.getChildAt(i);
        if(v instanceof Spinner)
        {
            // you got the spinner
            EditText s = (EditText) v;
            Log.i("Item selected",s.getText().toString());
        }
    }


回答3:

findViewById returns only the first view with the given id. You're going to have to traverse the view hierarchy yourself, at least until you get down to each horizontal linear layout. You'll find the methods ViewGroup.getChildCount() and ViewGroup.getChildAt(int) useful for this.