如何以编程方式创建EditText然后获取其值

时间:2014-10-01 06:58:41

标签: android android-edittext

我正在尝试以编程方式在表单中创建电话字段。如何识别并随后获得其价值?

创建EditText字段并添加到表单的代码是:

public void addTelephone(){           
          //form
          TableLayout table = (TableLayout)findViewById(R.id.table);
          //new row
          TableRow tr = new TableRow(NewRequestActivity.this);

          LayoutParams ltr = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
          ltr.setMargins(0, 0, 0, 2500);
          tr.setLayoutParams(ltr);
          //new field
          EditText et = new EditText(NewRequestActivity.this);
          et.setHint("telephone");
          et.setInputType(InputType.TYPE_CLASS_NUMBER);     
          et.requestFocus();
          Resources res = getResources();
          float fontSize = res.getDimension(R.dimen.input_form) / getResources().getDisplayMetrics().density;
          et.setTextSize(fontSize);

          LayoutParams let = new LayoutParams(0, LayoutParams.WRAP_CONTENT, 1);

          et.setLayoutParams(let);

          ImageView img = new ImageView(NewRequestActivity.this);
          img.setTag("img_"+counttelf);
          img.setImageResource(R.drawable.more);
          img.setBackgroundResource(R.drawable.imagefocused);
          img.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {               

                      v.setVisibility(View.GONE);
                      addTelephone();
                }
            });
          LayoutParams limg = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
          img.setLayoutParams(limg);

          tr.addView(et, 0);
          tr.addView(img, 1);
table.addView(tr, ++indextelf);
    }

2 个答案:

答案 0 :(得分:1)

您可以将标签设置为EditText

例如:

你有电话字段:

editText.setTag("phone");

当你想要检索它时。

做,

EditText ed = (EditText)findViewByTag("phone");
String text = ed.getText().toString(); 

答案 1 :(得分:0)

为每个动态创建的编辑文本设置Id,并参考其ID获取值。 设置Id:

edittext.setId(i);

从Id获取:

int i = edittext.getId();