如何在android中的自定义视图上添加按钮?

时间:2014-02-14 21:18:36

标签: android

如何在Android上的自定义视图中添加按钮?我正在使用自定义视图,但如果我使用图形布局向活动添加按钮它不起作用,我已将自定义视图放到活动上,所以它看起来像这样,但它仍然不会让我添加按钮

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    myView = new CustomView(this);
    myView.setGame(new Game());
    setContentView(myView);

    Button exitGameButton = new Button(this);
    exitGameButton .setGravity(Gravity.CENTER);
    exitGameButton .setText("Done");
    myView.addView(exitGameButton);
  }

然后它让我在我的customView

中添加了一个方法
    public void addView(Button exitGameButton) {
    // TODO Auto-generated method stub

}

按钮在我运行时不显示,现在如何将其更改为另一个活动?

1 个答案:

答案 0 :(得分:0)

以编程方式创建一个按钮

 Button myButton = new Button(this);

并添加到您的视图

   myView.addView(myButton);

更详细的例子:

private View v;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.main_layout, container, false);
    CustomView myCustomView = (CustomView) v.findViewById(R.id.customView1);
    //Create button. 
   Button myButton = new Button(this);
    //Add button to your custom view. 
    myCustomView.addView(myButton);