Android and android Official Website
We can usually set margin directly in xml, such:
<ImageView android: layout_margin = "5dip" android: src = "@ drawable/image"/>
However, in some cases, it needs to be written in java code, but the View itself does not have the setMargin method. What should I do?
After reading the android api, we found that android. view. ViewGroup. MarginLayoutParams has a setMargins (left, top, right, bottom) method ).
Its direct subclasses include: FrameLayout. LayoutParams, LinearLayout. LayoutParams and RelativeLayout. LayoutParams.
Usage:
LinearLayout. layoutParams lp = new LinearLayout. layoutParams (LinearLayout. layoutParams. WRAP_CONTENT, LinearLayout. layoutParams. WRAP_CONTENT); lp. setMargins (10, 20, 30, 40); imageView. setLayoutParams (lp );
If this method does not work, you can use the control that needs to modify margin, such as the previous imageView. There is a getLayout method, and the obtained layout can be strongly converted to LinearLayout or another type, then set the margin.
I am the dividing line of tiantiao
Reprinted