【发布时间】:2014-10-17 10:06:58
【问题描述】:
我想在 Java 中将 TextView 添加到 LinearLayout,但是一旦我访问 make_systematics() 中的 LinearLayout linlay_container,就会得到 NullPointerException。我有完全相同的代码来定义 LinearLayout 和 LinearLayout 内的 TextView textview_systematics。我可以访问 TextView,但不能访问 LinearLayout。这里有什么问题?
此布局是一个片段,包含在<fragment>-Tag 中,以防万一这很重要。
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");}
}
}
【问题讨论】:
标签: java android-fragments nullpointerexception android-linearlayout