How to set margin dynamically in Android?

后端 未结 5 2059
甜味超标
甜味超标 2020-12-25 11:19

I am currently doing an android application that contains customize alert dialog. It contains a button , but i can\'t set the margin for the button . the code is given belo

5条回答
  •  不思量自难忘°
    2020-12-25 11:35

    Just sharing a slightly different approach.

    Instead of casting to LinearLayout.LayoutParams, RelativeLayout.LayoutParams, etc, you can just cast to MarginLayoutParams.

    Casting to MarginLayoutParams is better because you can later update your layout and you don't need to return to your java code to change from LinearLayout to RelativeLayout or any other Layout type

    You can do something like:

    MarginLayoutParams layoutParams = (MarginLayoutParams) view.getLayoutParams();
    
    // Set bottom margin
    layoutParams.bottomMargin = x;
    
    // Set top margin
    layoutParams.topMargin = x;
    
    // Set left margin
    // This won't have effect if you set any relative margin (start) previously or in the layout.xml
    layoutParams.leftMargin = x;
    
    // Set left margin
    // This won't have effect if you set any relative margin (end) previously or in the layout.xml
    layoutParams.rightMargin = x;
    
    // Set start margin
    layoutParams.setMarginStart(x);
    
    // Set end margin
    layoutParams.setMarginStart(x);
    
    // Set all left, top, right, bottom margins at once
    // Note that here, left and right margins are set (not start/end).
    // So, if you have used start/end margin before (or via layout.xml), 
    // setting left/right here won't have any effect.
    layoutParams.setMargins(left, top, end, bottom)
    
    // Then re-apply the layout params again to force the view to be re-draw
    // This step may not be necessary because depending where you set the margin, 
    // view is already scheduled to be drawn
    // For any case, to ensure the view will apply the new margin, call:
    view.setLayoutParams(layoutParams);
    

提交回复
热议问题