简体   繁体   English

试图在片段中显示textview

[英]trying to display textview in fragment

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 是的,我知道有人问过我,但我的问题始终是null我尝试了所有方法,请尝试PLZ帮助,错误消息: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:

<?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%. 它应该正确地做到100%。 But, maybe you are inflating different layout and that's why TextView is null 但是,也许您正在夸大其他布局,这就是为什么TextView为null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM