我正在进行2D游戏,我想添加一个主菜单。目前,当我运行我的代码时,我的主要活动开始游戏循环。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set fullscreen
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// Set No Title
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setContentView(new GameSurface(this));
}
这是我的代码,我打算将setContentView()绑定到菜单中的播放按钮。实现我的菜单的最佳方法是什么,将其设置为不同的活动并在创建时加载它,然后通过意图将GameSurface的加载设置为另一个活动或者有更好的方法?
答案 0 :(得分:0)
将MainActivity设为主菜单,并创建单独的GameActivity。 例如:
你的main_activity.xml(菜单):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal"
android:background="@color/colorAccent"> <!-- define your custom background, f.e. html animation or picture -->
<Button
android:id="@+id/start_game"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start the game"
android:layout_marginTop="30dp" />
<Button
android:id="@+id/settings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Settings"
android:layout_marginTop="30dp" />
<Button
android:id="@+id/exit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Exit"
android:layout_marginTop="30dp" />
您的MainActivity(如果需要,您可以播放音乐或执行其他有用的操作):
public class MainActivity extends AppCompatActivity {
private Button startGame;
private Button settings;
private Button exit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startGame = (Button) findViewById(R.id.start_game);
startGame.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent game = new Intent(MainActivity.this, GameActivity.class);
startActivity(game);
}
});
settings = (Button) findViewById(R.id.settings);
settings.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent game = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(game);
}
});
exit = (Button) findViewById(R.id.exit);
exit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
System.exit(0);
}
});
}
}
你的GameActivity:
public class GameActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set fullscreen
this.getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// Set No Title
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setContentView(new GameSurface(this));
}