简体   繁体   中英

How to place a button in the center of Relative layout?

I'm trying to put a button on the center app ... Can someone explain to me what exactly this code is doing ?

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

What this code does is

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

Above line tells the view to occupy only the space it required.

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

The above two lines tell the LayoutManager to keep this view in Center both in horizontal and Vertical.

You should read about RelativeLayout and RelativeLayoutParams .

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);

I hope it will help you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM