"Problem description"
Android has the following code:
LinearLayout grouppollingaddress = (linearlayout) Findviewbyid (r.layout.fragment_field_list);
returns to null.
"Resolution Process"
1. For reference:
Android–getactivity (). Findviewbyid (R.layout.contacts_list_view) returns Null–stack Overflow
A quick solution to Findviewbyid return NULL in ANDROIDGUI27-the column of the mystery-the blog channel –csdn.net
But it's not done.
2. It was later to search:
Findviewbyid r.layout NULL
And finally find and refer to:
[Android]inflate method differs from Findviewbyid method | Layoutinflater's inflate function usage detailed –loyea– Blog Park
To change to:
Layoutinflater Inflater = (layoutinflater) tabcontext.getsystemservice (Context.layout_inflater_service);
LinearLayout grouppollingaddress = (linearlayout) inflater.inflate (r.layout.fragment_field_list, NULL);
Can.
3. Other, similar:
TextView Tab1allgrouppollingaddresslabel = (TextView) Findviewbyid (r.id.lblvariable);
is also returned null, so swap to:
TextView Tab1allgrouppollingaddresslabel = (TextView) Grouppollingaddress.findviewbyid (r.id.lblvariable);
Can.
Summary
Here Findviewbyid returns null for the following reasons:
Not in the parent who asks for find's son view.
Or is:
The view below, of course, does not contain the corresponding view that you want to find,
resulting in the result that cannot be found, returns NULL.
The solution is:
Find the parent or root view of the view you are looking for
Then look in the parent view to find the child view you want it.
The common wording is:
Layoutinflater Inflater = (layoutinflater) tabcontext.getsystemservice (context.layout_inflater_service);
LinearLayout grouppollingaddress = (linearlayout) inflater.inflate (r.layout.fragment_field_list, NULL);
The first is to find the layout of the current system, then instantiate it, and then look for your view in the global view to find it.
Ps:android A quick workaround for Findviewbyid in Custom view
On the internet are all in super (context, attrs); Constructors Here are a few more fields, in fact, it's not just one reason, it's the view lifecycle that you should know if you call Findviewbyid in the constructor of the custom view, which is definitely empty, Because this time the view is still in the initialization phase, has not been added to the activity of the XML layout, so how do you call it is useless, the solution is to change our Findviewbyid method for a lifecycle above call OK, for example, I was
protected void Onattachedtowindow () {
Called above.