0

我正在尝试在中心应用程序上放置一个按钮......有人可以向我解释这段代码到底在做什么吗?

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

2 回答 2

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的信息。

于 2015-05-13T09:33:40.083 回答
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);

我希望它会帮助你

于 2015-05-13T09:51:31.447 回答