How to get data from each dynamically created EditText in Android?

后端 未结 5 1083
盖世英雄少女心
盖世英雄少女心 2020-11-27 11:29

I have successfully created EditTexts depending on the user input in Android, and also I have assigned them unique ID\'s using setId() method.

Now wha

5条回答
  •  清歌不尽
    2020-11-27 11:42

    In every iteration you are rewriting the ed variable, so when loop is finished ed only points to the last EditText instance you created.

    You should store all references to all EditTexts:

    EditText ed;
    List allEds = new ArrayList();
    
    for (int i = 0; i < count; i++) {   
    
        ed = new EditText(Activity2.this);
        allEds.add(ed);
        ed.setBackgroundResource(R.color.blackOpacity);
        ed.setId(id);   
        ed.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
        linear.addView(ed);
    }
    

    Now allEds list hold references to all EditTexts, so you can iterate it and get all the data.

    Update:

    As per request:

    String[] strings = new String[](allEds.size());
    
    for(int i=0; i < allEds.size(); i++){
        string[i] = allEds.get(i).getText().toString();
    }
    

提交回复
热议问题