如何在java代码中设置margin属性

但是有些情况下,需要在java代码里来写,可是View本身没有setMargin方法,怎么办呢?

 

通过查阅android api,我们发现android.view.ViewGroup.MarginLayoutParams有个方法setMargins(left, top, right, bottom). 

其直接的子类有: FrameLayout.LayoutParams, LinearLayout.LayoutParams and RelativeLayout.LayoutParams.

 

使用方法:
Java代码 

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);  
    lp.setMargins(10, 20, 30, 40);  
    imageView.setLayoutParams(lp); 



Android如何在java代码中设置margin,也就是组件与组件之间的间距。


代码中设置:


 

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, 
                LayoutParams.FILL_PARENT); 
 params.setMargins(0, 5, 2, 0); 

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.FILL_PARENT);
 params.setMargins(0, 5, 2, 0);

 



你可能感兴趣的:(如何在java代码中设置margin属性)