I have two classes. The first is an Activity containing the usual layout. The second is a thread-based SurfaceView class. My question is exactly the same as this topic, but with Thread instead of AsyncTask:
Android/Java: Change view from another class?
When the thread causes certain events, I want to be able to update other Views in the Activity, but I cannot seem to find a method for correctly accessing those Views from within the SurfaceView.
public class MyActivity extends Activity{
Button myButton = (Button)findViewById(R.id.my_button);
...
}
public class MySurfaceView extends SurfaceView implements Runnable{
// Need code here that can access myButton to call myButton.setText("Some Text")
}
Most suggestions say something like this:
((Button)findViewById(R.id.my_button)).setText("My Text");
where the my_button is originally set up in the Activity’s onCreate(). However, this always results in a null pointer when called from within the SurfaceView. Further reasoning would tell me that I’d want to access the application context to find the View that way, but that seems to leave the door open for the dreaded context memory leak.
This seems like something that should be fairly common in Android programs, but I cannot seem to find a proper way of doing this.
Have you tried to implement a listener from SurfaceView that broadcasts event and setListener on the activity. Check here on how to implement http://tseng-blog.nge-web.net/blog/2009/02/17/how-implement-your-own-listener-android-java/