Add button on user view in Android

I have the following class

public class GameActivity extends Activity {
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      View gameView = new GameView(this);
      setContentView(gameView);
   }
}


and now I would like to add a button to my GameView class.

public GameView(Context context) {
        super(context);
// Code ...
}

I need this button during my game, so it should be alywas in front of all the other "I draw" canvas.
How can i do this?

+5
source share
2 answers

Do you want to create a new button?

Button b = new Button(context);
b.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, 
                                   LayoutParams.WRAP_CONTENT)); 

gameView.addView(b);

Use ViewGroupas GameViewparent insted simple view

ViewGroup gameView = new GameView(this);


public class GameView extends ViewGroup { //...
+1
source
View gameView = new GameView(this);

replace the above line with the following line:

View gameView = new GameView(this).createView();

and now in game viewing mode with a button, etc.

    public class GameView extends View {
    private Activity _activity;
    public GameView (Activity _activity) {
        super(_activity);
        // TODO Auto-generated constructor stub
        this._activity = _activity; 
    }
public View createView(){
        LinearLayout l = new LinearLayout(_activity);
        l.setOrientation(LinearLayout.VERTICAL);
        Button btn = new Button(_activity);
        btn.setId(1);
            btn.setText("btn"+(i+1));
        l.addView(btn);
        return l;
    }
}

try this working code:

0
source

All Articles