试图在片段中显示文本视图
trying to display textview in fragment
是的,我知道有人问过,但我的总是空的
我尝试了所有方法
请帮助,
错误按摩:
java.lang.NullPointerException: 尝试在空对象引用
上调用虚拟方法'void android.widget.TextView.setText(java.lang.CharSequence)'
public class InfoFragment extends Fragment {
private TextView tvInfo;
public InfoFragment(){};
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.main_fragment, container, false);
tvInfo = rootView.findViewById(R.id.tv_info);
tvInfo.setText("hello");
return rootView;
}
}
xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tv_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
您显示的代码是正确的。它应该 100% 做对。
但是,也许您正在夸大不同的布局,这就是 TextView 为 null
的原因
是的,我知道有人问过,但我的总是空的 我尝试了所有方法 请帮助, 错误按摩: java.lang.NullPointerException: 尝试在空对象引用
上调用虚拟方法'void android.widget.TextView.setText(java.lang.CharSequence)'public class InfoFragment extends Fragment {
private TextView tvInfo;
public InfoFragment(){};
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.main_fragment, container, false);
tvInfo = rootView.findViewById(R.id.tv_info);
tvInfo.setText("hello");
return rootView;
}
}
xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tv_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
您显示的代码是正确的。它应该 100% 做对。 但是,也许您正在夸大不同的布局,这就是 TextView 为 null
的原因