我正在开发 android 应用程序,在该应用程序中我在片段上创建动态布局。当用户单击按钮从布局元素获取数据时,我收到空指针异常错误。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_schedule, container, false);
parentLinearLayout=(LinearLayout) view.findViewById(R.id.parent_linear_layout);
add_field_button=(TextView) view.findViewById(R.id.add_field_button);
txtDate=(TextView) view.findViewById(R.id.txtDate);
txtTime=(TextView) view.findViewById(R.id.txtTime);
btnSubmit=(Button) view.findViewById(R.id.btnSubmit);
buttomclick(view);
return view;
}
我正在调用下面的函数以从动态布局中获取数据,并且在 EditText 上出现空指针异常。
ArrayList getEditTextList()
{
ArrayList<String> list = new ArrayList<String>();
int size = parentLinearLayout.getChildCount();
for (int i=0 ; i < size ; i++)
{
View view = parentLinearLayout.getChildAt(i);
EditText edtUsername = view.findViewById(R.id.edtVisitorname);
list.add(edtUsername.getText().toString());
String a ="";
}
return list;
}
单击下面的按钮时,我正在添加动态布局。
add_field_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onAddField(v);
}
});
public void onAddField(View v) {
LayoutInflater inflater=(LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView=inflater.inflate(R.layout.field, null);
// Add the new row before the add field button.
parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount() - 1);
}