我正在尝试从点击View
时添加到View
的孩子Button
中获取项目。但是,当我尝试获取已创建的子项View
中的元素时,它会返回null
。
java.lang.NullPointerException: Attempt to invoke virtual method'android.view.View android.view.View.findViewById(int)' on a null object reference
<Button
android:id="@+id/buttonAddPerson"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Add Another Person"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true" />
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/scrollView" >
<LinearLayout
android:id="@+id/linearLayoutPeople"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"></LinearLayout>
</ScrollView>
按钮点击添加的布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:layout_marginTop="5dp"
android:id="@+id/linearLayoutPerson">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editTextFirstName"
android:hint="First Name"
android:inputType="textPersonName"
/>
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_create_occupants, container, false);
Button addPersonButton = (Button)view.findViewById(R.id.buttonAddPerson);
root = (LinearLayout)view.findViewById(R.id.linearLayoutPeople);
View child = inflater.inflate(R.layout.list_person_layout,null);
root.addView(child);
addPersonButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// createPersonAdapter.notifyDataSetChanged();
View child = inflater.inflate(R.layout.list_person_layout,null);
root.addView(child);
}
});
return view;
}
当我尝试获取信息时:
public void SaveCall(){
EditText firstName;
for (int i =1;i<=root.getChildCount();i++){
View child = root.getChildAt(i);
//null at this line
firstName = (EditText) child.findViewById(R.id.editTextFirstName);
}
}
答案 0 :(得分:2)
你有没有试过这个
将此i<=root.getChildCount();
更改为i<root.getChildCount();
并从i=0;
for (int i =0;i<root.getChildCount();i++){
View child = root.getChildAt(i);
//null at this line
firstName = (EditText) child.findViewById(R.id.editTextFirstName);
}
答案 1 :(得分:0)
在动态创建视图时,可以将每个EditText添加到arrayList。然后通过该列表进行循环。