Search code examples
javaandroidsurfaceviewtoast

Toast in SurfaceView


I want to create a message with Toast inside a SurfaceView class. With this code I have the follow Exception ...

Toast toast = Toast.makeText(this.getContext(), "Message", Toast.LENGTH_LONG);
        toast.show();

11-05 02:06:08.070: ERROR/AndroidRuntime(265): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

How can I do a toast in SurfaceView ??


Solution

  • You need to show Toast with the UI thread. Whenever you initialize the SurfaceView, do something like this:

    Handler handler;
    private void initMe()
    {
        handler = new Handler();
    }
    

    Then, wherever you want to make the toast, do this:

    handler.post(new Runnable(){
        public void run(){
            Toast.makeText(context, "Message", Toast.LENGTH_LONG).show();
        }
    });
    

    You need to make sure "initMe" is called from the UI thread. You're probably initing the SurfaceView from onCreate, which is called by the UI thread, so you'd be good (I'm assuming this is a custom SufaceView extension class?)