There are setpadding in Android view, but there is no direct setmargin method. What to do if you want to set it in code?
can be set by setting the in view, layoutparams settings, and this layoutparams is based on the view in different Groupview and different.
The layout file is as follows:
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools " android:layout_width=" match_parent " android:layout_height=" Match_parent " > <linearlayout android:id= "@+id/ceshi_ly" android:layout_width= "Wrap_content" android: layout_height= "Wrap_content" android:background= "@android: Color/darker_gray" > <textview Android:id= "@+id/ceshi_tv" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:background= "@android: Color/holo_green_dark" android:text= "test dynamic settings margin"/> </ Linearlayout></relativelayout>
The code is as follows:
Package Com.android.testdemo;import Android.app.activity;import Android.os.bundle;import Android.widget.linearlayout;import Android.widget.linearlayout.layoutparams;import Android.widget.TextView; public class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); TextView Ceshitv = (TextView) Findviewbyid (R.ID.CESHI_TV); Linearlayout.layoutparams LP = (layoutparams) ceshitv.getlayoutparams () Lp.setmargins (30, 50, 22, 10); CESHITV.SETLAYOUTPARAMS (LP);}}
The effect is as follows:
Of course, it can be encapsulated as a method, as follows:
public static void SetMargins (View v, int l, int t, int r, int b) { if (v.getlayoutparams () instanceof Viewgroup.marg Inlayoutparams) { Viewgroup.marginlayoutparams p = (viewgroup.marginlayoutparams) v.getlayoutparams (); P.setmargins (L, T, R, b); V.requestlayout (); }}
Android Dynamic Settings margin