How to lay out Views in RelativeLayout programmatically?

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

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


   

        
9条回答
  •  天命终不由人
    2020-11-22 15:33

    This approach with ViewGroup.MarginLayoutParams worked for me:

    RelativeLayout myLayout = (RelativeLayout) findViewById(R.id.my_layout);
    
    TextView someTextView = ...
    
    int leftMargin = Util.getXPos();
    int topMargin = Util.getYPos();
    
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
        new ViewGroup.MarginLayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT));
    
    lp.setMargins(leftMargin, topMargin, 0, 0);
    
    myLayout.addView(someTextView, lp);
    

提交回复
热议问题