繁体   English   中英

在 textview 中显示来自 edittext 的值

[英]Display value from edittext in textview

我正在尝试在循环内以编程方式制作 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 如何从所有 EditTexts 中获取值?

您需要在EditText上调用addTextChangedListener(TextWatcher watcher) ,观察者将在每次更改时收到onTextChanged(CharSequence s, int start, int before, int count) ,您可以使用该序列来更新您的TextView 更多信息在这里: https://developer.android.com/reference/android/text/TextWatcher

有两个简单的步骤可以实现这一点:

  1. 创建时将您的EditText添加到某种列表中。
  2. 当某些事件(例如按钮单击)发生时,读取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());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM