在 android 中使用自定义 Toast 时黄色突出显示

Yellow highlight while using custom Toast in android

我正在尝试实现自定义 toast,下面是我编写的代码,并照常将其连接到 onClickeListner

Button customToastButton = (Button) this.findViewById(R.id.add_to_cart);
        customToastButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                //get the LayoutInflater and inflate the custom_toast layout
                LayoutInflater inflater = getLayoutInflater();
                View layout = inflater.inflate(R.layout.cart_toast, (ViewGroup)
                        findViewById(R.id.toast_layout_root));

                //get the TextView from the custom_toast layout
                TextView text = (TextView) layout.findViewById(R.id.toastText);
                text.setText("Item as been added to cart");

                //create the toast object, set display duration,
                //set the view as layout that's inflated above and then call show()
                Toast t = new Toast(getApplicationContext());
                t.setDuration(Toast.LENGTH_SHORT);
                t.setView(layout);
                t.show();
            }
        }); 

并且使用的代码以黄色突出显示,显示如下 error.well 它在 logcat 中没有显示为错误并且代码有效 fine.The highlightend 部分还说 ' 可能会产生'java.lang.NullPointerException'

Method invocation 'customToastButton.setOnClickListener(new View.OnClickListener() {             
public void onClick(Vi...' may produce 'java.lang.NullPointerException' less... (Ctrl+F1) 
    This inspection analyzes method control and data flow to report possible conditions that are always true or false, expressions whose value is statically proven to be constant, and situations that can lead to nullability contract violations.
    Variables, method parameters and return values marked as @Nullable or @NotNull are treated as nullable (or not-null, respectively) and used during the analysis to check nullability contracts, e.g. report possible NullPointerException errors.
    More complex contracts can be defined using @Contract annotation, for example:
    @Contract("_, null -> null") — method returns null if its second argument is null 
@Contract("_, null -> null; _, !null -> !null") — method returns null if its second argument is null and not-null otherwise 
@Contract("true -> fail") — a typical assertFalse method which throws an exception if true is passed to it 
    The inspection can be configured to use custom @Nullable
    @NotNull annotations (by default the ones from annotations.jar will be used)

我只是不明白导致这个错误的原因,请您看一下。 提前谢谢你

您可以在设置 OnClickListener

之前检查您的 customToastButton 是否不为空
if(customToastButton!=null){
    customToastButton.setOnClickListener(...)
...
}

显示警告,因为如果 Button 不存在并且您继续使用它,将抛出 NullPointerException