效果图:
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout relativeLayout = new RelativeLayout(this); // 创建相对布局对象
relativeLayout.setBackgroundColor(Color.rgb(0,0,255)); // 整个布局设置为蓝色
Button button = new Button(this); // 创建按钮对象
RelativeLayout.LayoutParams btnParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, // wrap_content
RelativeLayout.LayoutParams.WRAP_CONTENT); // wrap_content
btnParams.addRule(RelativeLayout.CENTER_HORIZONTAL); // 居中水平对齐
button.setLayoutParams(btnParams); // 将设定好的样式作为setLayoutParams方法的参数,设置给这个按钮
button.setText("按钮"); // 设置按钮名字
relativeLayout.addView(button); // 将按钮添加到相对布局容器中
setContentView(relativeLayout); // 再设定布局形式为相对布局
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
</LinearLayout>