在开发中遇到一个问题,是在一个自定义组件中用到了布局文件,而在代码中又用对布局文件中的一个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);
即将之前写好的布局参数读出来,然后再对其进行修改,就解决了这个问题。