Is it recommended to check view for null with every findViewById call?

后端 未结 2 825
青春惊慌失措
青春惊慌失措 2021-02-14 13:18

When inflating an element with findViewById, Android Studio always warns me that my inflated view may return null

View v = inflater.inflate(R.layou         


        
2条回答
  •  迷失自我
    2021-02-14 14:00

    You can ignore this warning and move ahead with your code if you are sure that the id you are passing does exist within your applications context, if you are not sure then its better to do a null check before accessing the elements in this view because

         View v = inflater.inflate(R.layout.fragment_photo_gallery, container, false);
    

    will return null in case "R.layout.fragment_photo_gallery" is incorrect or invalid renderring v as null .

    Thus an attempt like this

         mGridView = (GridView)v.findViewById(R.id.gridView);
    

    may result in a null pointer exception

提交回复
热议问题