我有一个名为 GameLoop 的 Activity(扩展 Activity 的类)。但我没有使用 xml 文件进行布局,而是使用一个类,因为我希望能够绘制到画布上。(我在一些教程上看到这是你应该做的)
布局类称为 GameLoopLayout。
我在布局类中运行了一个游戏循环,我可以将位图渲染到屏幕上并控制 FPS,一切都很好。但现在我想向其添加一个按钮,但由于我没有使用 xml 布局文件,所以我不知道该怎么做。有人可以帮我吗?
我在自动柜员机上做什么:
游戏循环布局:
Button button;
Canvas canvas;
SurfaceHolder surfaceHolder;
public GameLoopActivityLayout(Context context) {
//all necessary initializations here...
button = new Button(context);
button.setEnabled(true);
button.setLeft(10);
button.setTop(20);
}
//render function called during game loop
private void render() {
if (!surfaceHolder.getSurface().isValid())
return;
canvas = surfaceHolder.lockCanvas();
//draw all game objects to canvas...
button.draw(canvas);
surfaceHolder.unlockCanvasAndPost(canvas);
}
Run Code Online (Sandbox Code Playgroud)
尝试下面的代码:
LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayout2);
// add button
Button b = new Button(this);
b.setText("Button added dynamically!");
b.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
b.setId(MY_BUTTON);
b.setOnClickListener(this);
ll.addView(b);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
394 次 |
| 最近记录: |