Setmargin not working in relative layout in android

I created 2 buttons in a relative layout programmatically. I do not want to have a gap between the buttons and tried to achieve this using "setmargin", but could not. Below is the code.

//creating the relative layout RelativeLayout relativeLayout = new RelativeLayout(this); RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); //creating buttons Button button1 = new Button(this); button1.setId(R.id.button1); RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams( SCR_W/2, RelativeLayout.LayoutParams.WRAP_CONTENT);//SCR_W is the device screenwidth params1.addRule(RelativeLayout.ALIGN_PARENT_LEFT); params1.addRule(RelativeLayout.ALIGN_PARENT_TOP); params1.setMargins(0, 0, 0, 0); button1.setLayoutParams(params1); relativeLayout.addView(button1); Button button2 = new Button(this); button2.setId(R.id.button2); RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams( SCR_W/2, RelativeLayout.LayoutParams.WRAP_CONTENT); params2.addRule(RelativeLayout.ALIGN_PARENT_LEFT); params2.addRule(RelativeLayout.BELOW, button1.getId()); params2.setMargins(0, 0, 0, 0); button2.setLayoutParams(params2); relativeLayout.addView(button2); //setting the relative layout as the contentview setContentView(relativeLayout, rlp); 

Thanks in advance.

+4
source share
3 answers

I tried my code and it works fine,

Two buttons are at a distance of 0. To test this, simply set a different color for each button, and you will see that they are together.

 button1.setBackgroundColor(Color.BLUE); button2.setBackgroundColor(Color.RED); 
+2
source

Try setting the height of the relative layout to wrap_content ..

  RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
0
source

Just try something like this, it will work -:

  params1.setMargins(0, 0, 0, -5); params2.setMargins(0, -5, 0, 0); 
0
source

All Articles