代码动态设置间距,setMargins没有作用,出现无效的情况。

我的问题:在代码中动态添加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>


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值