java - Why findViewById() doesn't work as getActivity().findViewById() here? -
/** * placeholder fragment containing simple view. */ public static class placeholderfragment extends fragment { public placeholderfragment() { } @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view rootview = inflater.inflate(r.layout.fragment_detail, container, false); // detail activity called via intent. inspect intent forecast data. intent intent=getactivity().getintent(); textview text=(textview)rootview.findviewbyid(r.id.text1); string b=intent.getstringextra(intent.extra_text); text.settext(b); return rootview; } }
in code when using
textview text=(textview)getactivity().findviewbyid(r.id.text1)
then app crashes , logcat says that
caused by: java.lang.nullpointerexception: attempt invoke virtual method 'android.view.view android.view.window.findviewbyid(int)' on null object reference
this xml file associated code
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context="com.example.sunshine.app.detailactivity$placeholderfragment" > <textview android:id="@+id/text1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> </relativelayout>
in code when using textview text=(textview)getactivity().findviewbyid(r.id.text1)
then app crashes , logcat says caused by: java.lang.nullpointerexception: attempt invoke virtual method 'android.view.view android.view.window.findviewbyid(int)' on null object reference
findviewbyid()
on activity
starts root view (what referred "decor view") , traverses tree of available widgets , containers, looking id match. hence, findviewbyid()
called on activity
find views part of overall activity view hierarchy.
however, inflate()
call not attach inflated relativelayout
activity view hierarchy. expected. views attached activity view hierarchy when fragment attached, sometime after return oncreateview()
. result, when call findviewbyid()
on activity from inside oncreateview()
, cannot find textview
, because textview
being managed fragment , not yet part of activity view hierarchy.
findviewbyid()
on view
or viewgroup
starts view
or viewgroup
, traverses tree of available widgets , containers, looking id match. relativelayout
has access textview
, when call findviewbyid()
on relativelayout
inflate, works.
Comments
Post a Comment