How to align presentation elements in Relativelayout dynamically using code in Android?

I want to display 3 checkboxes one below the other in the relative layout dynamically using code. But I can only display two flags one below each other. I give below my code .... I cannot find out where I am going wrong.

My code is

RelativeLayout layout = new RelativeLayout(this); CheckBox cb1 = new CheckBox(this); cb1.setId(1); cb1.setText("A"); CheckBox cb2 = new CheckBox(this); cb2.setId(2); cb2.setText("B"); CheckBox cb3 = new CheckBox(this); cb3.setId(3); cb3.setText("C"); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); layout.setLayoutParams(lp); layout.addView(cb1); lp.addRule(RelativeLayout.BELOW,cb1.getId()); cb2.setLayoutParams(lp); layout.addView(cb2); lp.addRule(RelativeLayout.BELOW,cb2.getId()); cb3.setLayoutParams(lp); layout.addView(cb3); 

Thanks in advance.

Rohan wow

+4
source share
1 answer
 layout.addView(cb1); lp.addRule(RelativeLayout.BELOW,cb1.getId()); cb2.setLayoutParams(lp); layout.addView(cb2); lp.addRule(RelativeLayout.BELOW,cb2.getId()); cb3.setLayoutParams(lp); layout.addView(cb3); 

Thank you, this man helped me a lot.

I think you are mistaken in the sense that you use "lp" as the layout parameters for cb2 and cb3 (you cannot add the same rule "RelativeLayout.BELOW" to the same layoutpameters parameter "lp" and again) . Use lp for cb2 and lp2 for cb3 and create like this

  RelativeLayout layout = new RelativeLayout(this); CheckBox cb1 = new CheckBox(this); cb1.setId(1); cb1.setText("A"); CheckBox cb2 = new CheckBox(this); cb2.setId(2); cb2.setText("B"); CheckBox cb3 = new CheckBox(this); cb3.setId(3); cb3.setText("C"); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT); layout.setLayoutParams(lp); layout.addView(cb1); lp.addRule(RelativeLayout.BELOW,cb1.getId()); cb2.setLayoutParams(lp); layout.addView(cb2); RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);//important lp2.addRule(RelativeLayout.BELOW,cb2.getId());//important cb3.setLayoutParams(lp2);//important layout.addView(cb3); 

I think this will work.

+6
source

Source: https://habr.com/ru/post/1343412/


All Articles