问题
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'd like to add a Button to my class GameView.
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 canvas' I'm drawing.
How can I do that?
回答1:
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 ViewGroup
as GameView
parent insted of simple View
ViewGroup gameView = new GameView(this);
public class GameView extends ViewGroup { //...
回答2:
View gameView = new GameView(this);
replace the above line by below line::
View gameView = new GameView(this).createView();
and now in the Game view createview with button and 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:::
来源:https://stackoverflow.com/questions/10014780/add-button-on-custom-view-in-android