直接在Activity的布局xml文件中添加Button控件即可。示例代码如下:
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button1" />
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button2" />
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button3" />
如果想要动态添加button,则可以在代码中这样写:
Button button = new Button(this);
button.setId(100);
button.setText("button1");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "click", Toast.LENGTH_SHORT).show();
}
});
relativeLayout.addView(button);
其中,relativeLayout是在代码中声明的布局,然后你在MainActivity中设置this.setContentView(relativeLayout);就可以了。
无论你想要添加多少其他的控件,都可以按照上面的方法进行添加就可以了。