简体   繁体   English

在片段中声明 findViewById 后的 java.lang.NullpointerException

[英]java.lang.NullpointerException after declaring findViewById in fragment

I'm trying to use findViewById , but then a warning appears.我正在尝试使用findViewById ,但随后出现警告。 I've seen serveral different ways used to resolve this warning but I don't know which is correct when it comes to my code.我已经看到用于解决此警告的多种不同方法,但我不知道在我的代码中哪种方法是正确的。 Does anyone know what the correct way would be to remove this warning in this context?有谁知道在这种情况下删除此警告的正确方法是什么?

Method invocation 'findViewById' may produce 'java.lang.NullpointerException'方法调用“findViewById”可能会产生“java.lang.NullpointerException”

Page1Fragment.java Page1Fragment.java

public class Page1Fragment extends android.support.v4.app.Fragment {

    boolean squareState;

    public Page1Fragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_page1, container, false);
    }

    @Override
    public void onResume(){
        super.onResume();
        loadPreferences();
        displaySettings();
    }

    public void loadPreferences(){
        SharedPreferences pref =  this.getActivity().getSharedPreferences("settings", AppCompatActivity.MODE_PRIVATE);
        squareState = pref.getBoolean("square_state", true);
    }

    public void displaySettings() {
        if (squareState) {
            getView().findViewById(R.id.blue_square).setVisibility(View.VISIBLE);
        } else {
            getView().findViewById(R.id.blue_square).setVisibility(View.GONE);
        }
    }
}

I assume you're talking about a lint warning. 我假设你在谈论一个棉绒警告。

Depending on which part of the lifecycle the fragment is in, it may or may not have had its onCreateView method called yet. 根据片段所处的生命周期的哪个部分,它可能已经或者可能没有调用其onCreateView方法。

In the case that your fragment's view hasn't yet been created (onCreateView hasn't yet been called,) calls to getView() will return null. 如果尚未创建片段视图(尚未调用onCreateView),则对getView()的调用将返回null。

Thus, you'll need to check for null like so: 因此,您需要检查null,如下所示:

View contentView = getView();
if (contentView != null) {
    contentView.findViewById(R.id.blue_square).setVisibility(View.VISIBLE);
}

It's not always easy to know when a fragment is attached to an activity and its view has been created. 知道片段何时附加到活动并且其视图已创建并不总是很容易。 For example, if you've started an AsyncTask to retrieve some data on a background thread and then go to update the UI, the user may have navigated off of your fragment, and getView() will return null in this case. 例如,如果您已启动AsyncTask以在后台线程上检索某些数据然后再更新UI,则用户可能已从您的片段导航,并且在这种情况下getView()将返回null。

Have a look at the documentation for Fragment on developer.android.com for more information which details the fragment lifecycle. 有关详细说明片段生命周期的详细信息,请查看developer.android.com上Fragment的文档。

If you know where you're calling the getView() method, (after the onCreateView and before onDestroyView ), you can ignore those warnings. 如果您知道在哪里调用getView()方法(在onCreateViewonDestroyView之前),则可以忽略这些警告。 This method will be returning null outside these two callbacks. 此方法将在这两个回调之外返回null

A clean way to avoid checking it over and over again would be to pass the rootView as a reference to your dislplaySettings method. 避免一遍又一遍地检查它的一种干净方法是将rootView作为对dislplaySettings方法的引用传递。

public void displaySettings(View rootView) {
    if (squareState) {
        rootView.findViewById(R.id.blue_square).setVisibility(View.VISIBLE);
    } else {
        rootView.findViewById(R.id.blue_square).setVisibility(View.GONE);
    }
}

You'll get no complains when you use it inside the onResume as follows: 当您在onResume使用它时,您将不会抱怨,如下所示:

@Override
public void onResume() {
    displaySettings(getView()); // You're safe here!
}

Please refer to the Fragment life cycle docs . 请参阅Fragment生命周期文档

Bonus 奖金

To avoid some code duplication 避免一些代码重复

public void displaySettings(View rootView) {
    rootView.findViewById(R.id.blue_square).setVisibility(squareState ? View.VISIBLE : View.GONE);
}

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

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