习惯了直接在xml里设置margin(距离上下左右都是10dip),如:
只是有些情况下,需要在java代码里来写。
API中,android.view.ViewGroup.MarginLayoutParams有个方法setMargins(left, top, right, bottom)。可是View本身没有setMargin方法,怎么办呢?
看见API上,其直接的子类有: FrameLayout.LayoutParams, LinearLayout.LayoutParams and RelativeLayout.LayoutParams。我们我们可以这样写:
ImageView imageView = = new ImageView(getContext());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1); // , 1是可选写的
lp.setMargins(10, 20, 30, 40);
imageView.setLayoutParams(lp);