android - NPE when adding inflated button -


i try create new button programatically , existing viewgroup (i moved custom classical linearlayout ensure bug not in custom viewgroup).

a code simple , working in different use case:

private void appendtile() {     view view = getlayoutinflater().inflate(r.layout.template_tile, null);     view.setid(view.generateviewid());     view.setonclicklistener(tilelistener);     hiddenpicture.addview(view, view.getlayoutparams()); } 

template_tile.xml:

<button xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" style="@style/formulavalue" /> 

but fails, because view.getlayoutparams() null (though there layout_width , layout_height in xml).

caused by: java.lang.nullpointerexception: attempt read field 'int android.view.viewgroup$layoutparams.width' on null object reference    @ android.view.viewgroup$layoutparams.<init>(viewgroup.java:6453)    @ android.view.viewgroup$marginlayoutparams.<init>(viewgroup.java:6735)    @ android.widget.linearlayout$layoutparams.<init>(linearlayout.java:1901)    @ android.widget.linearlayout.generatelayoutparams(linearlayout.java:1799)    @ android.widget.linearlayout.generatelayoutparams(linearlayout.java:62)    @ android.view.viewgroup.addviewinner(viewgroup.java:3945)    @ android.view.viewgroup.addview(viewgroup.java:3786)    @ android.view.viewgroup.addview(viewgroup.java:3758)    @ lelisoft.com.lelimath.activities.puzzleactivity.appendtile(puzzleactivity.java:39)    @ lelisoft.com.lelimath.activities.puzzleactivity.oncreate(puzzleactivity.java:31) 

i went viewgroups constructor , reads width null params. shall differently in activity? why layout_width xml not set?

layoutparams specific container (i.e. viewgroup). since inflating without root parameter, layout parameters ignored, because there no "proper" way create suitable instance of layoutparams without knowing container type.

to use layout parameters xml, need supply root viewgroup when inflating:

view view = getlayoutinflater().inflate(     r.layout.template_tile,     hiddenpicture,     false // don't attachtoroot ); view.setid(view.generateviewid()); view.setonclicklistener(tilelistener); hiddenpicture.addview(view, view.getlayoutparams()); 

note third parameter attachtoroot false here. if set true, inflated view automatically attached parent container, simplifies typical case.

however, when attachtoroot == true return value inflate() not button instance hiddenpicture, i.e. supplied root view of affected hierarchy.

in case, never direct access button object. since manual setup (attach listener, set id) on inflated button, manual attach simpler.


Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -