我想在Java中将LinearView添加到LinearLayout,但是一旦我访问linlay_container
中的LinearLayout make_systematics()
,我就会得到一个NullPointerException。我有完全相同的代码用于在LinearLayout中定义LinearLayout和TextView textview_systematics
。我可以访问TextView,但不是 LinearLayout。这有什么不对?
这个布局是一个片段,包含在<fragment>
- 标签中,以防这可能很重要。
xml文件(fragment_species_systematics.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id = "@+id/linlay_fragment_species_systematics"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:orientation = "vertical" >
<TextView
android:id = "@+id/textView_fragment_species_systematics"
android:layout_width = "match_parent"
android:layout_height = "wrap_content" />
</LinearLayout>
Java文件:
public class Fragment_Species_Systematics extends Fragment {
LinearLayout linlay_container;
TextView textview_systematics;
View view;
public Fragment_Species_Systematics() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_species_systematics, container, false);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
linlay_container = (LinearLayout) getActivity().findViewById(R.id.linlay_fragment_species_systematics);
textview_systematics = (TextView) getActivity().findViewById(R.id.textView_fragment_species_systematics);
}
public void make_systematics(String json_systematics) {
if (textview_systematics.isAttachedToWindow()) {Log.i("DEBUG", "tv is attached");} else {Log.i("DEBUG", "tv is not attached");}
if (linlay_container.isAttachedToWindow()) {Log.i("DEBUG", "ll is attached");} else {Log.i("DEBUG", "ll is not attached");}
}
}
答案 0 :(得分:0)
想出来,遗憾的是没有找到任何理由为什么我做了以下事情:显然无法访问“全局”LinearLayout。我必须包含另一个LinearLayout并访问那个一个,然后才能工作。
我正在使用的xml文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" >
<LinearLayout
android:id = "@+id/linlay_fragment_species_systematics"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:orientation = "vertical" >
<TextView
android:id = "@+id/textView_fragment_species_systematics"
android:layout_width = "match_parent"
android:layout_height = "wrap_content" />
</LinearLayout>
</LinearLayout>