前台activity_main.xml: 一个普通的 hellowworld
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/Tv_Id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
后台 MainActivity.java
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
public class MainActivity extends Activity {
Button newButton; //新建按钮引用
int clickTimes = 0; //点击次数
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//设置按钮属性
newButton = new Button(this);
newButton.setWidth(100);
newButton.setHeight(100);
newButton.setPadding(40, 0, 0, 0);
newButton.setText("click me");
//设置按钮事件
newButton.setOnClickListener(new OnClickListener(){
public void onClick(View v)
{
clickTimes++;
newButton.setText(String.valueOf(clickTimes));
}
});
//得到当前布局
RelativeLayout relativeLayout = (RelativeLayout) getLayoutInflater().inflate(R.layout.activity_main, null);
//设置布局属性
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.BELOW, R.id.Tv_Id);
//添加按钮
relativeLayout.addView(newButton, layoutParams);
//设置布局
setContentView(relativeLayout);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}