android - Why is setting the text of a Spinner in onCreateView throwing a null pointer exception? -
i want set superficial text on spinner without having text appear item in spinner drop-down.
i'm getting reference spinner's textview this:
textview tv = (textview) spinner.findviewbyid(android.r.id.text1); tv.settext("test");
the problem throws npe when calling above code main body of oncreateview().
but if comment out these lines in main body of oncreateview(), works fine when set text using above code inside spinner's onitemselectedlistener
.
@override public view oncreateview(layoutinflater inflater, viewgroup parent, bundle savedinstancestate) { view v = inflater.inflate(r.layout.my_fragment, parent, false); spinner = (spinner) v.findviewbyid(r.id.myspinner); arrayadapter<charsequence> adapter = arrayadapter.createfromresource( getactivity(), r.array.options, r.layout.spinner_item); adapter.setdropdownviewresource(r.layout.spinner_dropdown_item); spinner.setadapter(adapter); spinner.setonitemselectedlistener(new onitemselectedlistener() { @override public void onitemselected(adapterview<?> parent, view view, int position, long id) { switch (position) { case 0: // works fine: textview tv = (textview) spinner.findviewbyid(android.r.id.text1); tv.settext("test"); break; } } @override public void onnothingselected(adapterview<?> arg0) { } }); // tv null on line below textview tv = (textview) spinner.findviewbyid(android.r.id.text1); tv.settext("test"); return v; }
the spinner not null. it's tv null.
does know why can't reference spinner's textview here, , how such reference?
edit:
i solved adding ongloballayoutlistener spinner's viewtreeobserver:
spinner.getviewtreeobserver().addongloballayoutlistener( new viewtreeobserver.ongloballayoutlistener() { @override public void ongloballayout() { spinner.getviewtreeobserver().removeglobalonlayoutlistener(this); textview tv = (textview) spinner.findviewbyid(android.r.id.text1); tv.settext("test"); } });
the views in spinner created part of layout pass happen on future iteration of main message queue. trying access view before created, findviewbyid returning null.
this put update on main queue, occurs after layout.
new handler(looper.getmainlooper()).post(new runnable() { @override public void run() { textview tv = (textview) spinner.findviewbyid(android.r.id.text1); tv.settext("test"); } });
a better approach might have custom subclass of spinner, need ( maybe in onlayout )
Comments
Post a Comment