Quick Solution of findViewById Returning Null null in Android

  • 2021-07-26 08:47:35
  • OfStack

[Problem Description]

The following code in Android:


LinearLayout groupPollingAddress = (LinearLayout)findViewById(R.layout.fragment_field_list);

Returns null.

[Resolution process]

1. Reference:

android getActivity (). findViewById (R. layout. contacts_list_view) returns null Stack Overflow

findViewById in AndroidGUI27 returns the quick solution of null. The column blog channel CSDN.NET of Mystery Yishi

But it didn't work out.

2. Later, I went to search:

findViewById R.layout null

And finally find and refer to:

[Android] The difference between inflate method and findViewById method inflate function usage of LayoutInflater detailed explanation of loyea blog garden

To replace it with:

LayoutInflater inflater = (LayoutInflater)tabContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout groupPollingAddress = (LinearLayout)inflater.inflate(R.layout.fragment_field_list, null);

That's enough.

3. In addition, similar:

TextView tab1AllGroupPollingAddressLabel = (TextView) findViewById(R.id.lblVariable);

It also returns to null, so replace it with:

TextView tab1AllGroupPollingAddressLabel = (TextView) groupPollingAddress.findViewById(R.id.lblVariable);
That's enough.

[Summary]

Here findViewById returns as null because:

It was not found in Parent requesting view of find

Or is it:

Of course, under View, there is no corresponding view you are looking for.

As a result, it cannot be found and returns null.

The solution is:

Find parent of view or view of root

Find the child view you want in the parent view.

The common way to write it is:


LayoutInflater inflater = (LayoutInflater)tabContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout groupPollingAddress = (LinearLayout)inflater.inflate(R.layout.fragment_field_list, null);

Which is first to find the current system Layout, and then instantiation, and then in the global view to find your view can be found.

PS: Android Custom Quick Solution to Empty findViewById in view

What is said on the Internet is in super (context, attrs); The constructor adds one less field here, In fact, there is more than one reason at all. Belong to the view lifecycle should know, if you call findViewById in the constructor of the custom view iron is empty, because this time view is still in the initialization stage, has not been added to the XML layout of activity, so how you call is useless, the solution is to change our findViewById method for a lifecycle above call on OK, for example, I am in


 protected void onAttachedToWindow() {
super.onAttachedToWindow();} 

Called above


Related articles: