码迷,mamicode.com
首页 > 移动开发 > 详细

转--Android如何在java代码中设置margin

时间:2015-03-11 21:24:29      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

http://www.2cto.com/kf/201207/140111.html

红黑联盟:

习惯了直接在xml里设置margin(距离上下左右都是10dip),如:

 <ImageView android:layout_margin="10dip" android:src="@drawable/image" />

只是有些情况下,需要在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); 

 

转--Android如何在java代码中设置margin

标签:

原文地址:http://www.cnblogs.com/awkflf11/p/4330825.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!