Android 子视图的findViewById
我试图从一个子Android 子视图的findViewById,android,android-layout,Android,Android Layout,我试图从一个子视图中获取项目,单击按钮时,该子视图被添加到视图。但是,当我试图在创建的子视图中获取元素时,它返回一个null java.lang.NullPointerException: Attempt to invoke virtual method'android.view.View android.view.View.findViewById(int)' on a null object reference 当我试图获取信息时: public void SaveCall(){
视图
中获取项目,单击按钮
时,该子视图被添加到视图
。但是,当我试图在创建的子视图中获取元素时,它返回一个null
java.lang.NullPointerException: Attempt to invoke virtual method'android.view.View android.view.View.findViewById(int)' on a null object reference
当我试图获取信息时:
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);
}
}
public void SaveCall(){
编辑文本名;
对于(inti=1;i你是这样尝试的吗
更改此i动态创建视图时,可以将每个EditText添加到arrayList。然后在该列表中执行for循环。为什么会导致NPE?如果root.getChildCount()是4,然后尝试从第4个位置获取子项。因为第4个位置为null。因此它必须是null指针。如果我错了,请告诉我。“i”的范围必须从0到getChildCount()-1。崩溃的原因可能是您试图访问1个位置太远,并且getChildAt()对于无效的位置返回null。@BladeCoder是的,如果我们使用i将循环更改为建议的工作状态,您是对的,不确定我在想什么,将其设置为i=1。谢谢@Amsheer
<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);
}
}
for (int i =0;i<root.getChildCount();i++){
View child = root.getChildAt(i);
//null at this line
firstName = (EditText) child.findViewById(R.id.editTextFirstName);
}