效果图
MainActivity中
package com.zhh.centertest;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.RelativeLayout;
public class MainActivity extends Activity {
// 相对布局
private RelativeLayout rlBuJu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rlBuJu = findViewById(R.id.rlBuJu);
// 实例化一个按钮对象
Button button = new Button(this);
button.setText("居中");
// 实例化一个layoutParams,
// 如果父布局是相对布局则RelativeLayout.LayoutParams
// 如果父布局是线性布局则是LinearLayout.LayoutParams
RelativeLayout.LayoutParams layoutParams =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
// 居中
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
// 设置属性
button.setLayoutParams(layoutParams);
// 把按钮添加到布局中
rlBuJu.addView(button);
}
}
activity_main中
<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"
tools:context=".MainActivity"
android:id="@+id/rlBuJu"
>
</RelativeLayout>