Android(安卓)-- java代码设置margin
16lz
2021-12-04
我们平常可以直接在xml里设置margin,如:
<ImageView android:layout_margin="5dip" android:src="@drawable/image" />
但是有些情况下,需要在java代码里来写,可是View本身没有setMargin方法,怎么办呢?
通过查阅android api,我们发现android.view.ViewGroup.MarginLayoutParams有个方法setMargins(left, top, right, bottom).
其直接的子类有: FrameLayout.LayoutParams, LinearLayout.LayoutParams and RelativeLayout.LayoutParams.
使用方法:
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); lp.setMargins(10, 20, 30, 40); imageView.setLayoutParams(lp);
如果这个方法没有效果的话,可以用需要修改margin的控件,就比如前面的imageView,有一个getLayout方法,获得的layout在强转类型到LinearLayout或者其他,然后再设定margin的。
我是天王盖地虎的分割线
转载
更多相关文章
- 在android的Browser中设置User Agent
- Android滑动手势侦测方法介绍
- Activity背景色为透明的2种方法
- Android(安卓)RecycleView
- 2011.09.07(5)——— android 跨进程通信之content provider + Aut
- Binder解析
- Android入门篇一:Android(安卓)Activity生命周期
- Android单元测试
- 2011.09.07(5)——— android 跨进程通信之content provider + Aut