我正在尝试在循环内以编程方式制作EditText。
我目前正在做什么:
public class MainActivity extends Activity {
int quan = 0;
LinearLayout linear;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for (int i =0; i < quan; i++)
{
EditText myEditText = new EditText(this);
myEditText.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
linear.addView(myEditText);
}
}
}
但是我想存储所有EditTexts中的值,并在某些TextView中显示它们如何从所有EditText获取值?
您需要在addTextChangedListener(TextWatcher watcher)
上调用EditText
,观察者将在每次更改时收到onTextChanged(CharSequence s, int start, int before, int count)
,您可以使用顺序来更新TextView
。此处更多信息:https://developer.android.com/reference/android/text/TextWatcher
有两个简单的步骤可以实现这一点:
EditText
时将它们添加到某种列表中。foreach
中的值。我使用StringBuilder减少了在堆字符串池中创建的字符串的数量。
// 1 - Add all of your EditTexts inside some ArrayList as a member of class
private ArrayList mEditTexts = new ArrayList<EditText>();
// 2 - Add your EditTexts to @mEditTexts when you are creating them
...
...
mEditTexts.add(editText);
// 3 - In your event handler, when you need to get all values
StringBuilder stringBuilder = new StringBuilder()
for(EditText editText : mEditTexts) {
String content = editText.getText().toString().trim();
stringBuilder.append(content);
}
textView.setText(stringBuilder.toString());