Wednesday, 6 June 2012

How to align view elements in Relativelayout dynamically through code in Android?

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

No comments:

Post a Comment