繁体   English   中英

Android片段和null对象引用

[英]Android fragment and null object reference

我试图让我的片段工作,我无法完成任何我想做的事情。

我得到的错误是:

java.lang.NullPointerException:尝试在空对象引用上调用虚方法'void android.widget.TextView.setText(java.lang.CharSequence)'

这是代码:

public class FragmentOne extends Fragment {

    private TextView one;

    public FragmentOne() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        one = (TextView) getActivity().findViewById(R.id.one);

        // Displaying the user details on the screen
        one.setText("kjhbguhjg");

    }

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

    }
}

不知道为什么它不起作用。 我正在测试这个类只是为了查看文本是否会在textview上更改。 我正在使用正确的id,因为我检查了10次,但我认为问题是因为textview one是一个null对象。 但为什么它没有找到id?

onCreate()onCreateView()之前调用,因此您将无法在onCreate()访问它。

解决方案:移动

one = (TextView) getActivity().findViewById(R.id.one);

改为onViewCreated()

有关片段生命周期的概述,请参见下图。

新的代码片段如下所示:

public class FragmentOne extends Fragment {


    private TextView one;

    public FragmentOne() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

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

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState){
        one = (TextView) getActivity().findViewById(R.id.one);
        // Displaying the user details on the screen
        one.setText("kjhbguhjg");
    }
}

片段生命周期

要么。 而不是重写

public void onViewCreated(View view, Bundle savedInstanceState)

你可以稍微改变你的onCreateView,看起来像

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment1, container, false)
one = (TextView) rootView.findViewById(R.id.one)
return rootView;
}

暂无
暂无

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

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