Android 相对布局中的 代码中修改属性与布局文件的设置不同的解决方法

在开发中遇到一个问题,是在一个自定义组件中用到了布局文件,而在代码中又用对布局文件中的一个ImageView设置了 layoutParams,如下代码

RelativeLayout.LayoutParams layoutParams =new LayoutParams(typedArray.getDimensionPixelSize(R.styleable.CustomActionBar_cab_image_width, 42), typedArray.getDimensionPixelSize(R.styleable.CustomActionBar_cab_image_height, 18));
image_title.setLayoutParams(layoutParams);

而结果导致我在布局文件中设置的ImageVIew的layout_centerInParent=”true”效果没有了。

<ImageView
        android:id="@+id/image_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/title_word_register"
        />

后来想了想,是因为重新对ImageView进行了布局参数的设置,而新的布局参数是新new的一个,它没有关于之前设置的任何布局参数,所以解决方案如下:

RelativeLayout.LayoutParams layoutParams = (LayoutParams)image_title.getLayoutParams();

        layoutParams.width = typedArray.getDimensionPixelSize(R.styleable.CustomActionBar_cab_image_width, 42);
        layoutParams.height = typedArray.getDimensionPixelSize(R.styleable.CustomActionBar_cab_image_height, 18);
        image_title.setLayoutParams(layoutParams);

即将之前写好的布局参数读出来,然后再对其进行修改,就解决了这个问题。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值