首页 > 解决方案 > 'android.view.View android.widget.TextView.findViewById(int)' 在空对象引用上

问题描述

当我在 android studio 的片段中调用 findViewById 时出现此错误

“尝试在 com.example.apptrail4.profile_frg.onCreateView() 的空对象引用上调用虚拟方法 'android.view.View android.widget.TextView.findViewById(int)'”

  @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    F2F_fragment = inflater.inflate(R.layout.fragment_profile_frg, container, false);

  

    String abc = "Hello sir";
    nametxt = nametxt.findViewById(R.id.nameshow);
    nametxt.setText(abc);


    return F2F_fragment;
}

标签: androidfragmentfindviewbyid

解决方案


你应该使用F2F_fragment.findViewById(...). 您必须在父视图中找到您之前已经膨胀的子视图,而不是在其内部


推荐阅读