is there possible to give marginTop as much as views height at xml?

92 Views Asked by At

I have one imageView and I am trying to give it minus margin top as much as its height / 2. I can do it at programmatically but i wondred is it possible at xml also andorid published percentrelative layout . I don't know how to to do it or possible?

1

There are 1 best solutions below

2
On

--Edit: As @aga suggests, there seems to be a way to achieve it via the Percent Support Library--

If you want to use this type of imageView more often throughout your application you could extend imageview and put your margin-code inside of it's onMeasure:

public class HalfMarginImageView extends ImageView {

    public HalfMarginImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        ((ViewGroup.MarginLayoutParams) getLayoutParams()).topMargin = -getMeasuredHeight() / 2;
    }
}

for this to work the view must be part of a ViewGroup.Also make sure you use the constructor with AttributeSet, oltherwise you can't create the View from xml. Yo then just include a CustomView in your layout xml, select HalfMarginImageView and use it as normal imageView.