Programmatically add view one below other in relative layout

前端 未结 3 682
一个人的身影
一个人的身影 2020-11-27 18:49

I want something like this programmatically:

view1 |  view2
view3 |  view4
----------------
view1 |  view2
view3 |  view4
----------------
view1 |  view2
vie         


        
3条回答
  •  暖寄归人
    2020-11-27 19:00

    Instead of using multiple layout params as suggested in @Askilondz answer, you can use addRule and removeRule as below:

    RelativeLayout rl = new RelativeLayout(this.getContext());
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,                                                                                     
                                LayoutParams.WRAP_CONTENT);
    TextView tv1 = new TextView(this);
    tv1.setId(View.generateViewId());
    tv1.setText("textView1");
    
    TextView tv2 = new TextView(this);
    tv2.setId(View.generateViewId());
    tv2.setText("textView2");
    lp.addRule(RelativeLayout.BELOW, tv1.getId());
    rl.addView(tv2, lp);
    lp.removeRule(RelativeLayout.BELOW);
    .
    .
    .
    

    If you are using SDK < 17, you have to create id's.xml file, as values -> ids.xml with structure like:

    
    
        
        
    
    

    and set them in your code as:

    tv1.setId(R.id.tv1);
    tv2.setId(R.id.tv2);
    

    UPDATE It looks the Adding multiple rules for the same LayoutParams not working fine, anyhow, I'll keep my answer in case someone fine something usefull in it for him

提交回复
热议问题