您好,在下面的片段上单击我的列表视图,得到空指针。 如果它是正常活动,则可以正常工作。它使我的应用程序崩溃了
任何人都可以帮助我在哪里弄错了。
public class HomeFragement extends Fragment {
EditText et_building;
TextView Add;
ListView lv;
ArrayList<String> arrayList;
ArrayAdapter<String> adapter;
public HomeFragement() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
((NavigationViewActivity) getActivity()).setActionBarTitle("ADD BUILDING");
View rootView = inflater.inflate(R.layout.activity_building, container, false);
init();
return rootView;
}
private void clickListener() {
Add.setOnClickListener (new View.OnClickListener ( ) {
@Override
public void onClick(View v) {
String result=et_building.getText ().toString ();
arrayList.add (result);
adapter.notifyDataSetChanged ();
}
});
}
private void init() {
et_building=(EditText)getActivity ().findViewById (R.id.build_name);
Add=(TextView)getActivity ().findViewById (R.id.addbuild);
lv=(ListView)getActivity ().findViewById (R.id.list_building);
arrayList=new ArrayList<String> ();
adapter=new ArrayAdapter<String> (getActivity (),android.R.layout.simple_list_item_1,arrayList);
lv.setAdapter(adapter);
clickListener();
}
答案 0 :(得分:0)
发现问题-声明ID时出现问题。使用
rootView
代替getActivity()
这样做
init(rootView);
这个方法应该是
private void init(View rootView ) {
et_building=(EditText)rootView.findViewById (R.id.build_name);
Add=(TextView)rootView.findViewById (R.id.addbuild);
lv=(ListView)rootView.findViewById (R.id.list_building);
arrayList=new ArrayList<String> ();
adapter=new ArrayAdapter<String> (getActivity (),android.R.layout.simple_list_item_1,arrayList);
lv.setAdapter(adapter);
clickListener();
}
答案 1 :(得分:0)
尝试将您的init()
代码放在onCreateView()
内,例如:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
((NavigationViewActivity) getActivity()).setActionBarTitle("ADD BUILDING");
View rootView = inflater.inflate(R.layout.activity_building, container, false);
et_building=(EditText)rootView.findViewById (R.id.build_name);
Add=(TextView)rootView.findViewById (R.id.addbuild);
lv=(ListView)rootView.findViewById (R.id.list_building);
arrayList=new ArrayList<String> ();
adapter=new ArrayAdapter<String> (getActivity(),android.R.layout.simple_list_item_1,arrayList);
lv.setAdapter(adapter);
return rootView;
}
并使用rootView
代替getActivity()
创建新对象