yes I know it has been asked but mine is always null I tried all ways plz help, the error massage: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
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>
The code you showed is correct. It should be doing it right 100%. But, maybe you are inflating different layout and that's why TextView is null
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.