在strings.xml文件中
<resources>
<string name="app_name">ButtonTest</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
<string name="addbtn1">添加水平按钮</string>
<string name="addbtn2">添加垂直按钮</string>
</resources>
在activity_main.xml文件中
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:text="@string/addbtn1"
android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:text="@string/addbtn2"
android:id="@+id/Button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<LinearLayout
android:id="@+id/LinearLayout01"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</LinearLayout>
<LinearLayout
android:id="@+id/LinearLayout02"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</LinearLayout>
</LinearLayout>
在MainActivity.java中
package com.example.buttontest;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
Button addhorizontal_Button;
Button addvertical_Button;
LinearLayout horizontal_11;
LinearLayout vertical_11;
int count_horizontal;
int count_vertical;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addhorizontal_Button=(Button)findViewById(R.id.Button01);
addhorizontal_Button.setOnClickListener(
new OnClickListener()
{
public void onClick(View v)
{
Button tempButton=new Button(MainActivity.this);
String result="添加水平按钮"+(++count_horizontal);
tempButton.setText(result);
horizontal_11=(LinearLayout)findViewById(R.id.LinearLayout01);
horizontal_11.addView(tempButton);
}
}
);
addvertical_Button=(Button)findViewById(R.id.Button02);
addvertical_Button.setOnClickListener(
new OnClickListener()
{
public void onClick(View v)
{
Button tempButton=new Button(MainActivity.this);
String result="添加垂直控件"+(++count_vertical);
tempButton.setText(result);
vertical_11=(LinearLayout)findViewById(R.id.LinearLayout02);
vertical_11.addView(tempButton);
}
}
);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}