Android,View设置margin
16lz
2022-05-22
android的view中有setPadding,但是没有直接的setMargin方法。如果要在代码中设置该怎么做呢?
可以通过设置view里面的 LayoutParams 设置,而这个LayoutParams是根据该view在不同的GroupView而不同的。
ImageView image = (ImageView) findViewById(R.id.main_image);RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(image.getLayoutParams());lp.setMargins(50, 100, 0, 0);image.setLayoutParams(lp);
这里的RelativeLayout是说明该view在一个RelativeLayout里面。 可以把设置margin的方式封装成方法,只要是GroupView里面的LayoutParams 即可。
public static void setMargins (View v, int l, int t, int r, int b) { if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) { ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams(); p.setMargins(l, t, r, b); v.requestLayout(); }}
一劳永逸。 更多相关文章
- Android——最新LitePal使用
- android 实现屏幕截图
- android
- Android(安卓)应用语言设置的实现
- 一个不错的启动菜单显示屏动画效果
- 【Android】OpenGL ES for Android(安卓)教程1 - HelloWorld
- Android(安卓)CPU使用率:top和dump cpuinfo的不同
- android 权限大全
- SAP BSP, Java Web Project,Android和微信小程序的初始页面设置