FindViewById In A Subclassed SurfaceView Throwing RuntimeException
Solution 1:
You are crashing because your TextView
is null after findViewById()
. The TextView
is not a child of the SurfaceView
, therefore calling findViewById()
with the SurfaceView
as the starting point will not find it.
Solution 2:
You can cast the context as an Activity and find the view as follows:
(TextView) ((Activity) context).findViewById(R.id.contents);
Now it won't be null.
Solution 3:
I was having the same problem and the answer provided by Loke resolved my issue. I don't know if casting is a good clean way to program for android sdk. here is what my code ended up like:
my activity had:
setContentView(R.layout.game);
my game.xml:
<TextView
android:text="@string/text_foul_counter_1"
android:layout_height="wrap_content"
android:background="#fff"
android:gravity="center"
android:textColor="#000"
android:id="@+id/TextViewFoulCounter1"
android:layout_width="wrap_content"
android:layout_below="@+id/TextViewFoul1"
android:padding="2dp"></TextView>
and calling finViewById from within my class: public class PlayerView extends Activity implements OnClickListener, OnLongClickListener {...}
without casting I used to get a null pointer exception. below is the code line that works now.
foulsTextViewTeam1 = (TextView) ((Activity) context).findViewById(R.id.TextViewFoulCounter1);
Post a Comment for "FindViewById In A Subclassed SurfaceView Throwing RuntimeException"