0

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);
mpromonet
  • 11,326
  • 43
  • 62
  • 91
yeo4
  • 356
  • 1
  • 4
  • 12

2 Answers2

2

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.

Manish
  • 1,215
  • 10
  • 29
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);

I hope it will help you

Nam Hoang
  • 46
  • 3