Add Button on custom View in Android

柔情痞子 提交于 2020-01-13 09:50:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!