从动态生成的 Edittext 中获取输入值

Son*_*ery 2 android android-layout android-edittext

我必须创建 nEditText其中 n 是用户输入。

我可以使用for循环创建它。

TableLayout tbl=(TableLayout)findViewById(R.id.TableLayout1);
    //table row
    for (int i = 0; i < 5; i++) {
        TableRow tr = new TableRow(this);
        TableLayout.LayoutParams tableRowParams=
                new TableLayout.LayoutParams
                (TableLayout.LayoutParams.FILL_PARENT,TableLayout.LayoutParams.WRAP_CONTENT);
        //for set margin
        tableRowParams.setMargins(0, 10, 0, 0);
        tr.setLayoutParams(tableRowParams);
        tr.setGravity(Gravity.CENTER_HORIZONTAL);
        //text view
        TextView tv=new TextView(this);
        tv.setText("Field "+(i+1));
        tv.setGravity(Gravity.CENTER);
        tv.setTextColor(Color.parseColor("#0070C0"));
        tv.setTextSize(26);
        tv.setLayoutParams(new TableRow.LayoutParams(100, TableRow.LayoutParams.WRAP_CONTENT));
        //add textview
        tr.addView(tv);
        //set layout params of edittext
        TableRow.LayoutParams etParams=
                new TableRow.LayoutParams
                (120,30);
        etParams.setMargins(10, 0, 0, 0);

        EditText et=new EditText(this);
        et.setLayoutParams(etParams);
        et.setBackgroundResource(R.drawable.bg_grey);
        et.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
        tr.addView(et);
        tbl.addView(tr, tableRowParams);
    }
Run Code Online (Sandbox Code Playgroud)

我有布局

在此处输入图片说明

让我知道如何从动态创建的 EditTexts 中检索数据。

小智 5

添加编辑文本

//list to store edittexts
List<EditText> etList = new ArrayList<EditText>();
TableLayout tbl=(TableLayout)findViewById(R.id.table);
for(int i=1;i<=5;i++){
    TableRow tr = new TableRow(CurrentActivity.this);  
    TableLayout.LayoutParams tableRowParams=
        new TableLayout.LayoutParams
        (TableLayout.LayoutParams.FILL_PARENT,TableLayout.LayoutParams.WRAP_CONTENT);       
    EditText et=new EditText(CurrentActivity.this);
    et.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL|InputType.TYPE_CLASS_NUMBER);
    et.setId(Id+i);//string+i
    //add et to table row
    tr.addView(et);
    //add table row to table            
    tbl.addView(tr, tableRowParams);
    //add edittext to list
    etList.add(et);
}
Run Code Online (Sandbox Code Playgroud)

获取值

for (EditText et : etList) {
    System.out.println(et.getText().toString());
}
Run Code Online (Sandbox Code Playgroud)