I have an include like:
The include layout looks like (te
I just wanted to add to this for future Googlers, I had kind of the opposite problem where the root layout of the included xml (in this case outer), was null when calling findViewById(), but the children of outer were not null.
The problem was solved for me by removing the id property of the include
'view' (in this case placeHolder). When that was gone, I could find outer but it's id :)
If you need a an id assigned to the include
item, I think it's better to wrap it in another viewgroup.
Can you try then finding the outer parent (lets call it 'op') and then try op.findViewById() ?
I found the answer to this problem.
This problem arises when we set both the Incloud ID and the first inner layer.
I used merge to solve the problem.
<include
android:id="@+id/layout_stories"
layout="@layout/layout_stories" />
and in layout_stories
<merge>
<LinearLayout
android:id="@+id/llItem">
...
</LinearLayout>
<merge>
Future researchers: https://stackoverflow.com/a/1760010/2790016 when you add an id to it overwrites the id from the outer tag from the "real layout"
Given that most constraint layouts need an id to positions items, removing the id from include is not an ideal answer.
I had the same problem. I found out that I used a wrong function with the same name with 2 parameters as following:
public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.activity_ble_connecting);
//findViewByid() => wrong
}
correct function with only one parameters:
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ble_connecting);
//findViewByid() => correct
}
If you have given the id to the include
element and you have only single view in the included layout (not in any ViewGroup
), in my case AdView
, then use the id of include
element instead of included view.
<?xml version="1.0" encoding="utf-8"?>
<!--adview.xml-->
<com.google.android.gms.ads.AdView
xmlns:ads="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
ads:adSize="BANNER"
ads:adUnitId="@string/admob_banner_id">
</com.google.android.gms.ads.AdView>
activity_main.xml
<include
layout="@layout/adview"
android:id="@+id/adsLayout"
/>
In activity
AdView nullAdView=findViewById(R.id.adView); //this will give null
AdView adView = findViewById(R.id.adsLayout); //this will be AdView
If you do not give id
to include
element then it is ok to use view id
. Also if your view
is inside any ViewGroup
like FrameLayout
then it is ok to use view id
.