android - Why findViewById() is returning null if setcontentview() is not called? -
i new-bee android.
here xml file -
<linearlayout 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" tools:context=".mainactivity" android:id="@+id/linearlayout" android:orientation="vertical"> <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" android:id="@+id/textview" /> </linearlayout>
and basic code -
@override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); view view=getlayoutinflater().inflate(r.layout.activity_main,null); //setcontentview(view); linearlayout ly = (linearlayout)findviewbyid(r.id.linearlayout); log.i("system.out ","linear layout = " + view); log.i("system.out ","linear layout = " + ly); }
output:
05-10 11:44:15.996: i/system.out(6494): linear layout = android.widget.linearlayout@41e34db8 05-10 11:44:15.996: i/system.out(6494): linear layout = null
findviewbyid()
returning null? why?
if uncomment setcontentview(view)
, run again ..
output:
05-10 11:50:12.781: i/system.out(7791): linear layout = android.widget.linearlayout@41e0d6c8 05-10 11:50:12.781: i/system.out(7791): linear layout = android.widget.linearlayout@41e0d6c8
what setcontentview()
doing?
public void setcontentview (view view)
set activity content explicit view. view placed directly activity's view hierarchy.
setcontentview (view view) method of activity class. when activity created need set content activity.
oncreate(bundle) initialize activity. importantly, here call setcontentview(view) layout resource defining ui, , using findviewbyid(int) retrieve widgets in ui need interact programmatically.
your implementation of oncreate() should define user interface , possibly instantiate class-scope variables.
every resource text view ,drawables when added in layout files have entry in r.java files entry automatic
example
for activity_main in r.java
public static final class layout { public static final int activity_main=0x7f030000; }
in case inflating layout not setting content activity.
you need set content activity , find ids using findviewbyid(..).
if not nullpointerexception.
Comments
Post a Comment