我的问题:在代码中动态添加view ,然后设置margin 的时候,有时候会出现setMargin 无效的情况。
我这边出现这个情况的原因是:
我的父控件是LinearLayout ,但是有些时候你在新建 LayoutParams 的时候,它使用的是RelativeLayout.LayoutParams。这个时候你通过LayoutParams .setMargin 就会出现不起作用的情况。所以大家可以检查一下看看是不是这个原因,写代码要注意一下。
之前网上查资料的时候,有这样一些的情况,也给大家列一下:
资料 出处:https://blog.csdn.net/lebsharing/article/details/53413884
一、在4.0以下的系统中给FrameLayout的子view设置margin失效
失效原因:失效原因应该是4.0及以上Framelayout的默认的layout_gravity设置好了"top|left"或有类似逻辑,而4.0以下则没有,所以才会失效。
解决方案:
1、在布局中给View设置,加入android:layout_gravity="top|left",
2、在代码中解决margin失效问题。
FrameLayout.LayoutParams p =
new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
p.gravity = Gravity.TOP;view.setLayoutParams(p)
二、在RelativeLayout 中设置某些情况下的子view,android:layout_marginBottom无效。
如:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageView android:id="@+id/avatar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="8dp"/> </RelativeLayout>这样设置,在部分设备上marginBottom无效。
原因:在这个view的下面已经没有子view,marin_bottom没有相对控件。
解决方案:在ImageView下面加一个view就可以,改view的宽高可以设置为0。这样就解决了问题。如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageView android:id="@+id/avatar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="8dp"/> <View android:layout_width="0px" android:layout_height="0px" android:layout_below="@id/avatar"/> </RelativeLayout>