How to lay out Views in RelativeLayout programmatically?

前端 未结 9 1693
心在旅途
心在旅途 2020-11-22 15:04

I\'m trying to achieve the following programmatically (rather than declaratively via XML):


   

        
相关标签:
9条回答
  • 2020-11-22 15:42

    Just spent 4 hours with this problem. Finally realized that you must not use zero as view id. You would think that it is allowed as NO_ID == -1, but things tend to go haywire if you give it to your view...

    0 讨论(0)
  • 2020-11-22 15:51

    Try:

    EditText edt = (EditText) findViewById(R.id.YourEditText);
    RelativeLayout.LayoutParams lp =
        new RelativeLayout.LayoutParams
        (
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT
        );
    lp.setMargins(25, 0, 0, 0); // move 25 px to right (increase left margin)
    edt.setLayoutParams(lp); // lp.setMargins(left, top, right, bottom);
    
    0 讨论(0)
  • 2020-11-22 15:53

    From what I've been able to piece together, you have to add the view using LayoutParams.

    LinearLayout linearLayout = new LinearLayout(this);
    
    RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
            LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    relativeParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    
    parentView.addView(linearLayout, relativeParams);
    

    All credit to sechastain, to relatively position your items programmatically you have to assign ids to them.

    TextView tv1 = new TextView(this);
    tv1.setId(1);
    TextView tv2 = new TextView(this);
    tv2.setId(2);
    

    Then addRule(RelativeLayout.RIGHT_OF, tv1.getId());

    0 讨论(0)
提交回复
热议问题