开发者

TextEdit Text Input Issues in my game

I am working on an Android game and am currently trying to get text input working. I want to prompt the player to enter his or her name and have that name added to the high score list.

I am trying to do that through EditText which I can get to work if I put my code in the onCreate method, but not if I call it from my game loop.

The method I am currently using:

public static void getInput(Context context)
{
    final AlertDialog.Builder alert = new AlertDialog.Builder(context);
    final EditText input = new EditText(context);

    alert.setView(input);
    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() 
    {
        public void onClick(DialogInterface dialog, int whichButton) 开发者_开发问答
        {
            String value = input.getText().toString().trim();
        }
    });

    alert.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() 
            {
                public void onClick(DialogInterface dialog, int whichButton) {
                    dialog.cancel();
                }
            });
    alert.show();
}

If I call this from my gameloop the game crashes and I get the error:

01-26 06:33:21.413: ERROR/AndroidRuntime(6960): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

I tried calling Looper.prepare() and then Looper.loop(), and that opened up the text input box, but when I closed the box my game just sat on a black screen and did not respond.

So, my question is: what am I doing wrong, and is there an easier way to get text input? My game is based off the LunarLander example, so I am using SurfaceView.

Any help or suggestions will be appreciated. Thank you :)


Hi Smills: your question should thread problem.any change on UI should down with the UI thread.you can use handler to post your intent that prompt users do something . handler in your gameloop function can post a message,and the same handler handlemessage on your UI thread,then change your UI.

the example like this:

declare a global variable:

Handler mHandler;

your function(){

 Message msg = Message.obtain();
 msg.what = your flag ;
 handler.post(msg);

}


You you have access to you activity, try wrapping the dialog code in a runnable and call runOnUiThread(dialogRunnable). Your other options are to start a handler in your activity onCreate and then post a request to the handler. But perhaps you just want to create a dialog activity (and activity using the theme android:theme="@android:style/Theme.Dialog") and just use startActivity.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜