Programmatically set margin for TableRow

前端 未结 2 602
走了就别回头了
走了就别回头了 2020-12-08 16:25

I have TableRows created dynamically in the code and I want to set margins for these TableRows.

My TableRows created as follow

相关标签:
2条回答
  • 2020-12-08 16:43

    You have to setup LayoutParams properly. Margin is a property of layout and not the TableRow , so you have to set the desired margins in the LayoutParams.

    Heres a sample code:

    TableRow tr = new TableRow(this);  
    TableLayout.LayoutParams tableRowParams=
      new TableLayout.LayoutParams
      (TableLayout.LayoutParams.FILL_PARENT,TableLayout.LayoutParams.WRAP_CONTENT);
    
    int leftMargin=10;
    int topMargin=2;
    int rightMargin=10;
    int bottomMargin=2;
    
    tableRowParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);
    
    tr.setLayoutParams(tableRowParams);
    
    0 讨论(0)
  • 2020-12-08 16:49

    This is working:

    TableRow tr = new TableRow(...);
    TableLayout.LayoutParams lp = 
    new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
                                 TableLayout.LayoutParams.WRAP_CONTENT);
    
    lp.setMargins(10,10,10,10);             
    tr.setLayoutParams(lp);
    
    ------
    
    // the key is here!
    yourTableLayoutInstance.addView(tr, lp);
    

    You need to add your TableRow to TableLayout passing the layout parameters again!

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