2016-05-06 2 views
0

私はActivityLoop(Activityを拡張するクラス)を持っています。 しかし、レイアウトにxmlファイルを使用する代わりに、私はキャンバスに描画できるようにするため、クラスを使用しています。 (私はいくつかのチュートリアルを見てきましたが、これはあなたがやるべきことです)Android - プログラムボタンを作成

レイアウトクラスはGameLoopLayoutと呼ばれています。

私はレイアウトクラスでゲームループを実行しています。私は画面にビットマップをレンダリングし、FPSを制御することができます。 しかし、今、私はそれにボタンを追加するが、私はXMLレイアウトファイルを使用していないので、私はそれを行う方法がわからない。誰でも私を助けてくれますか?

私は気圧やってる:

GameLoopLayout:コードの下に

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); 
} 

答えて

1

カスタムビューを作成すると、XMLのレイアウトを持っていることからあなたを防ぐことはできません。たとえば:

<FrameLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <com.yourpackage.GameLoopLayout 
     android:id="@+id/game_loop_layout" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" /> 

    <Button 
     android:id="@+id/button" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     ... /> 

</FrameLayout> 

あなたが好きな場所のボタンを配置するためにマージンやandroid:layout_gravityを使用することができます。これがどのように動作するかを説明するの

// inside of onCreate() 
mGameLoopLayout = (GameLoopLayout) findViewById(R.id.game_loop_layout); 
// do setup with GameLoopLayout 
+0

[コメントが削除されました] – jorgemf

+0

私はかなり失われていますが、どういうわけか私はそれを仕事にしました。ここで何がやっているのか教えてください。 onCreateメソッドは次のとおりです。 setContentView(R.layout.game_loop); レイアウト=(GameLoopLayout)findViewById(R.id.game_loop_layout); – Tirafesi

+0

@Tirafesiあなたは何について混乱していますか?これはアンドロイドでUIを行う標準的な方法です。 'setContentView()'にXMLレイアウトを渡すと、XMLで設定したIDでビューをルックアップします。それはすべて起こっていることです。 – Karakuri

4

を試してみてください。

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); 
+0

ケア:コードで

、あなたのようなあなたのGameLoopLayoutへのアクセスを得るには、他のビューをでしょうか? linearLayout2とは何ですか、どこで入手できますか?同じ質問id My_BUTTON – Tirafesi

+0

@Tirafesiプライベートstatic final int MY_BUTTON = 100;あなたのコードにこれを加えてください。 –

関連する問題