如何正确使用if语句为inflater null checker

时间:2018-05-12 23:14:06

标签: java android xml nullpointerexception layout-inflater

尝试以编程方式创建CardView后,NullPointerException但我使用了if语句并且警告消失了,但我不确定需要在{{1}中进行什么操作if语句的一部分。

  

方法调用'膨胀'可能会产生java.lang.NullPointerException

爪哇

else

XML

//start of CardView
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(LAYOUT_INFLATER_SERVICE);
if(inflater1 != null) {
View inflatedCardviewLayout = inflater.inflate(R.layout.my_cardview,  new RelativeLayout(getContext()), false);
inflatedCardviewLayout.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.green));

TextView cv_tv1a = inflatedCardviewLayout.findViewById(R.id.cardview_titleA);
cv_tv1a.setText(getString(R.string.titleA));

ImageView imgPictogram = inflatedCardviewLayout.findViewById(R.id.image_pictogram);
imgPictogram.setImageResource(R.drawable.ic_pictogram);

TextView cv_tv1b = inflatedCardviewLayout.findViewById(R.id.cardview_titleB);
cv_tv1b.setText(getString(R.string.titleB));
} else {
    //do something else
}
//end of CardView

1 个答案:

答案 0 :(得分:0)

您应该修复NullPointerException,因为获取inflater是代码的必需用途。我的意思是使用LayoutInflator.from(parent context)进行修复,而不是向系统询问。

您应该创建一个类,以便扩展CardView,然后使用创建视图对象时的上下文来获取inflater。还要确保将CardView与充气布局合并!