我如何getText()从编程文本创建的edittext

时间:2014-08-12 12:49:45

标签: android android-edittext

我以编程方式创建两个edittext,我需要从他那里获取文本 这是我创建edittext的代码

layoutParams = new LinearLayout.LayoutParams(
     LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

layoutParams.setMargins(10, 10, 10, 10);

//First EditText
edText = new EditText(getActivity());
edText.setId(0);  
edText.setLayoutParams(new LinearLayout.LayoutParams(
      LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT,
      1f));

edText.setBackgroundResource(R.drawable.edittext);
edText.setPadding(5, 5, 5, 5);

linear=(LinearLayout)rootView.findViewById(R.id.edittextpanel);
linear.addView(edText ,layoutParams);

nb++;

//Second EditText           
edText = new EditText(getActivity());
edText.setId(1);  
edText.setLayoutParams(new LinearLayout.LayoutParams(
                  LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT,
                  1f));

edText.setPadding(5, 5, 5, 5);
edText.setBackgroundResource(R.drawable.edittext);       
linear.addView(edText ,layoutParams);

请帮助我被阻止

3 个答案:

答案 0 :(得分:4)

edText = new EditText(getActivity());

edText.setId(id);

String stringAnswer = edText.getText().toString();

如果您想创建和引用多个编辑文本,您必须创建一个EditText数组

List<EditText> allEDs = new ArrayList<EditText>();

然后创建编辑文本

edText = new EditText(getActivity());

edText.setId(id);

将它们推入数组

allEDs.add(edText);

创建一个与EditText数组相同大小的字符串数组

String[] ETResults = new String[allEDs.size()];

循环通过EditText数组并将转换后的结果放入String数组

for(int i=0; i < allEDs.size(); i++){
        ETResults[i] = allEDs.get(i).getText().toString();
}

然后将所需的字符串分配给您想要的任何内容

String stringAnswer = ETResults[i];

答案 1 :(得分:1)

try {
        final ViewGroup viewGroup = (ViewGroup) ((ViewGroup) context.findViewById(android.R.id.content)).getChildAt(0);
        for(int i = 0; i <viewGroup.getChildCount(); i++){
            if(viewGroup.getChildAt(i) instanceof EditText) {
                EditText view = (EditText)viewGroup.getChildAt(i);
                Log.i("val " , " val " + ((EditText) viewGroup.getChildAt(i)).getText() + "  view  "+ view.getText() );
            }
        }
    }catch (Exception ex){
        Log.e("Error in Bind layout", ex.toString());
    }

答案 2 :(得分:0)

保留对EditTexts的引用。将以下内容放在Fragment的主体中,以使其可以全局访问..

EditText edText1;
EditText edText2;

然后在您展示的方法中,您可以使用...

// Do some stuff

edText1 = new EditText(getActivity());

// Do some more stuff

edText2 = new EditText(getActivity());

...

稍后当您需要获取文本时,您可以使用...

String text1 = edText1.getText().toString();
String text2 = edText2.getText().toString();

或者,您可以稍后使用他们的ID FragmentLinearLayout linear = (LinearLayout) findViewById(R.id.edittextpanel); EditText et = (EditText) linear.findViewById(0); String text1 = et.getText().toString(); et = (EditText) linear.findViewById(1); String text2 = et.getText().toString(); 中找到它们。

{{1}}