[英]Display value from edittext in textview
I'm trying to make EditText programmatically inside a loop.我正在尝试在循环内以编程方式制作 EditText。
What I'm currently doing:我目前在做什么:
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);
}
}
}
but I want to store the value from all EditTexts and display them in some TextView how I can get values from all EditTexts?但我想存储来自所有 EditTexts 的值并将它们显示在一些 TextView 如何从所有 EditTexts 中获取值?
You need to call addTextChangedListener(TextWatcher watcher)
on your EditText
, the watcher will receive onTextChanged(CharSequence s, int start, int before, int count)
on every change, and you can use the sequence to update your TextView
.您需要在
EditText
上调用addTextChangedListener(TextWatcher watcher)
,观察者将在每次更改时收到onTextChanged(CharSequence s, int start, int before, int count)
,您可以使用该序列来更新您的TextView
。 More information here: https://developer.android.com/reference/android/text/TextWatcher更多信息在这里: https://developer.android.com/reference/android/text/TextWatcher
There are two easy steps to achieve this:有两个简单的步骤可以实现这一点:
EditText
s to some kind of List when creating them.EditText
添加到某种列表中。foreach
when some event (eg button click) happens.foreach
中的值。 I used StringBuilder to reduce the number of Strings created in heap String Pool.我使用 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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.