gpt4 book ai didi

android - 如何从动态 edittext 和 radio 组中获取值?

转载 作者:行者123 更新时间:2023-11-30 00:19:15 25 4
gpt4 key购买 nike

我已经创建了动态 View 。该 View 包含两个 edittext 和一个 radio 组。当我单击添加按钮时, View 将添加到布局中。现在我很困惑,如何从这些类型的动态 View 中获取值。我试过了,但没有用。当我添加两个或多个 View 时,循环找不到下一个 View 值。我想将该值添加到 ArrayList。这是代码:

私有(private)无效 addDynamicViews() {

EditText name = new EditText(this);
EditText mobile = new EditText(this);

LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
p.setMargins(10, 10, 5, 5);

name.setLayoutParams(p);
name.setBackgroundResource(R.drawable.edittext_box);
name.setHint("Enter Name");
studentslayout.addView(name);

mobile.setLayoutParams(p);
mobile.setBackgroundResource(R.drawable.edittext_box);
mobile.setHint("Enter Mobile No");
studentslayout.addView(mobile);

/* radioGroup - Radio Group
maleButton,femaleButton - Radio Buttons
studentslayout - Linear Layout */

radioGroup = new RadioGroup(this);
radioGroup.setOrientation(RadioGroup.VERTICAL);
maleButton = new RadioButton(this);
maleButton.setText("Male");
radioGroup.addView(maleButton);

femaleButton = new RadioButton(this);
radioGroup.addView(femaleButton);
femaleButton.setText("Female");
studentslayout.addView(radioGroup);
}

如何获取所有动态的 edittext 和 radio group 值?我试过这段代码但不幸的是它停止了。

 @Override
public void onClick(View v) {

String[] array = new String[studentslayout.getChildCount()];
int count = studentslayout.getChildCount();
for (int i=0; i < studentslayout.getChildCount(); i++){

editText = (EditText)studentslayout.getChildAt(i);
array[i] = editText.getText().toString();

RadioButton radValues = (RadioButton) studentslayout.getChildAt(i);
array[i] = radValues.getText().toString();

}
}

最佳答案

RadioButton radValues = (RadioButton) studentslayout.getChildAt(i);

您已经添加了 radioGroup 并且需要 radiobutton。此外,由于您正在循环,因此您应该检查 View 的类型。

你可以尝试这样的事情:

int childCount = studentslayout.getChildCount();
for (int i = 0; i < childCount; i++) {
View childView = studentslayout.getChildAt(i);
if (childView instanceof EditText) {
EditText editText = (EditText) childView;
String text = editText.getText().toString();
//use text
} else if (childView instanceof RadioGroup) {
RadioGroup radioGroup = (RadioGroup) childView;
int radioCount = radioGroup.getChildCount();
for (int j = 0; j < radioCount; j++) {
RadioButton radioButton = (RadioButton) radioGroup.getChildAt(i);
//use radioButton.
}
}
}

关于android - 如何从动态 edittext 和 radio 组中获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46618915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com