How to solve the problem that findViewById gets the control to return to null in Android

  • 2021-07-24 11:49:43
  • OfStack

In the Android program, it is sometimes necessary to load controls that are not in the xml layout in the original activity to enrich the interface of the Android program.

I myself encountered problems in using ViewFlipper.


public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); 
inflater=(LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.myview, null);
ImageView view=(ImageView)findViewById(R.id.imageview); 
} 

As we all know, we call findViewById to get the control elements in the layout, but when I run, I find that there is an error of java. lang. NullPointerException. 1 At first I thought that the fetched view was still empty, but finally I found that the fetched ImageView was empty. Because id of myview and imageview has been successfully generated in R. java. After 1 time of search query, we found that when we rewrote the getView () function of Adapter, we got 1 control element through


holder.imageView=(ImageView)convertView.findViewById(R.id.imageView); 

In this form to get.

So it occurred to me that if I called the findViewById method directly in activity, its full form would be this. findViewById (). And the control I needed did not exist in the layout of the activity itself, so I changed it when I got it to


ImageView view=(ImageView)view.findViewById(R.id.imageview); 

That is, you can get the correct control by calling the findViewById method through the view where the control is located.

This is not a big problem in itself, but if you don't pay attention to it, you will still spend 1 fixed time. Here I just take notes for myself and provide convenience for friends who develop Android.


Related articles: