create dyanamic rule

2019-03-03 18:10发布

问题:

I am trying to dynamically resize an image which is in the relative layout using the code

int height = v.getHeight();
   int width = v.getWidth();
height += 50;
width += 50; 
RelativeLayout.LayoutParams layout = new RelativeLayout.LayoutParams(height, width);
layout.setMargins(200, 200, 200, 200);
layout.addRule(RelativeLayout.CENTER_IN_PARENT);
    v.setLayoutParams(layout);

Here v is a view (a imageView in this case) The rule works perfectly. The image gets placed in the center but what i want to get is the image should be placed where it is. That is if the image is at the location (100,100) it's size should be increased and the image should be placed at the same location or the location where i need to place it. Can anyone suggest me please.

回答1:

What you are asking, can't be done simply by creating rules. You need to do the extra work for such alignment.

1) use addRule to align parent left & align parent top, then set the left and top margin to align the image to any position you want 100,100 or 200, 50 etc. after that you can resize the image without changing position.

2) if you keep the image aligned CENTER_IN_PARENT then the image resize is a bit typical. you need to increase the left and top padding according to the increased size to align the image in center.

suppose image size is 100x100 and new size is 150x150
now you need to set layout parameters to width x height to 200x200 and set the left and top padding of image to 50.

I hope its clear