Should I put my code in the Activity or the View?
I'm fiddling around with making my first game for Android, but I'm having a lot of difficulties. To me, the API seems a bit strange at some points (for example Dialog boxes - why would they have to go through events...) but I'm slowly learning.
But right now, I'm a bit lost. I'm not sure where to put my code exactly, and I don't really know how to figure out what the best way is.
I have made my own View, GameView, which does the drawing in the onDraw event. I also put most of my code into the GameView. For example when you touch the View (in the onTouch event) I handle it and perform 开发者_如何学Goactions.
However now I want to display a standard Dialog box, and I read it has to be done through an Activity, with showDialog and the onDialog event. I was a bit confused that I'm not directly able to just show dialog boxes through the View.
So I started thinking, maybe I'm doing this all wrong... maybe I shouldn't put all my code into the View, but rather put my code in the Activity? When I went through the API Dialog examples, they just fetch the Buttons from the XML and attach events to them, etc, all inside the Activiy.
I hope my question/problem is a bit clear. I'm not sure which code should go where, and how to interact between the Activity and the (Game)View, etc.
It's hard to say whether you're design is good or not, but I wouldn't worry too much.
The LunarLander sample has very little code in the Activity
(only creating the menu basically) and most of the game logic is indeed implemented in the View
. Of course, you should have as less as possible in the onDraw()
method itself if you want a responsive game.
you should create an xml with layout. It will contain the GameView that will be aware of the activity it is shown within. So, when you have detected for ex. touch event in your GameView, you would be able to ask activity to show the dialog. See the concept:
public void MyActivtiy extends Activity {
@Override
public void onCreate() {
// your initialization
GameView view = (GameView) findViewById(R.id.gameView);
view.setCalledActivity(this);
}
}
public GameView extends View {
private Context context;
public void setCalledActivity(Context context) {
this.context = context;
}
@Override
public void onTouchEvent(...) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MyActivity.this.finish();
}
}) ;
AlertDialog alert = builder.create();
alert.show();
}
}
精彩评论