我动态地在LinearLayout中创建了EditBox。这是我的代码:
final LinearLayout mainLayout = (LinearLayout) findViewById(R.id.main_relative);
counter = 0;
addButt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
counter += 1;
LinearLayout ll = new LinearLayout(view.getContext());
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.setTag(CONSTANT_LAYOUT + counter);
LinearLayout.LayoutParams layoutParams = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(30, 20, 30, 0);
EditText etProduct = new EditText(view.getContext());
etProduct.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
etProduct.setTag(counter);
ll.addView(etProduct);
mainLayout.addView(ll);
}
它就像一个魅力。每当我点击特定按钮时,它会创建新的线性布局,其中的EditBox和计数器逐个增加,用户可以在 EditBox es中添加值。
现在,我希望获得 EditBox es的价值,我尝试过:
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
for (int i=0 ; i<counter ; i++) {
View lr = mainLayout.findViewWithTag(CONSTANT_LAYOUT+i);
EditText et = (EditText)lr.findViewWithTag(counter);
}
}
});
}
但我收到了一个错误:
致命异常:主程序:com.myapp,PID:15055 java.lang.NullPointerException:尝试调用虚方法 “android.view.View null对象上的android.view.View.findViewWithTag(java.lang.Object)' 参考
有什么建议吗?
答案 0 :(得分:1)
请尝试将您的for
loop
设为1而不是0,并尝试将标记值设置为大于1或equal
为1而不是0。
for (int i=1 ; i<=counter ; i++) { // and condition should be i<=counter = instead of less than
View lr = mainLayout.findViewWithTag(CONSTANT_LAYOUT+i);
EditText et = (EditText)lr.findViewWithTag(counter);
}
答案 1 :(得分:1)
你的循环从零开始。
for (int i=0 ; i<counter ; i++) {
// No value for Zero index.
}
在设置代码时,您正在添加+1。所以第一个值将是1而不是0。
counter += 1; // Default value of counter is zero
答案 2 :(得分:1)
您已在根目录LinearLayout
中添加了新的LinearLayout
。您也可以setId()
向新创建的LinearLayout
而不是setTag()
也可以为您工作。
LinearLayout ll = new LinearLayout(view.getContext());
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.setId(CONSTANT_LAYOUT + counter);
LinearLayout.LayoutParams layoutParams = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(30, 20, 30, 0);
EditText etProduct = new EditText(view.getContext());
etProduct.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
etProduct.setId(counter);
ll.addView(etProduct);
mainLayout.addView(ll);
并且
for (int i=0 ; i<counter ; i++) {
LinearLayout ll = (LinearLayout )mainLayout.findViewById(CONSTANT_LAYOUT+i);
EditText et = (EditText)ll .findViewById(counter);
}