I am trying to use relative layout in my app. With two TextViews and a Button. Here’s the xml file:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:padding="30dip"
android:orientation="vertical">
<TextView
android:id="@+id/up"
android:text="@string/start_game"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
/>
<TextView
android:id="@+id/level"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_below="@id/up"/>
/>
<Button android:id="@+id/start"
android:text = "@string/go"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_alignParentBottom="true"
/>
</RelativeLayout>
Now, the TextView with id=up shows perfectly. For the second TextView (with id=level) i want to add text to it via my java code. Here’s what i did:
TextView text = (TextView) findViewById(R.id.level);
text.setText("Hello Android");
But this crashes the program. What is my mistake here?
So that’s it… you must always call
setContentViewbefore usingfindViewById.