如何在相对布局的中心放置一个按钮?

时间:2015-05-13 09:29:57

标签: java android xml relativelayout center-align

我试图在中心应用上添加一个按钮... 有人可以向我解释这段代码到底在做什么吗?

RelativeLayout.LayoutParams BD = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT
    );
    BD.addRule(RelativeLayout.CENTER_HORIZONTAL);
    BD.addRule(RelativeLayout.CENTER_VERTICAL);

2 个答案:

答案 0 :(得分:2)

此代码的作用是

RelativeLayout.LayoutParams BD = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.WRAP_CONTENT,
        RelativeLayout.LayoutParams.WRAP_CONTENT
);

上面一行告诉视图只占用它所需的空间。

BD.addRule(RelativeLayout.CENTER_HORIZONTAL);
BD.addRule(RelativeLayout.CENTER_VERTICAL);

以上两行告诉LayoutManager将此视图保持在水平和垂直中心。

您应该阅读RelativeLayoutRelativeLayoutParams

答案 1 :(得分:0)

RelativeLayout relativeLayout;
Button btnNewButton;
relativeLayout = new RelativeLayout(getApplicationContext());
    btnNewButton = new Button(getApplicationContext());
    btnNewButton.setText("Button Text");

    RelativeLayout.LayoutParams BD = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT
    );
    BD.addRule(RelativeLayout.CENTER_HORIZONTAL);
    BD.addRule(RelativeLayout.CENTER_VERTICAL);

    btnNewButton.setLayoutParams(BD);

    relativeLayout.addView(btnNewButton);
    setContentView(relativeLayout);

我希望它能帮到你