Kristy Welsh
Kristy Welsh

Reputation: 8340

Is there a way to tell programmatically which type of layout is a view's parent

I have an ImageView that I am resizing dynamically and I need to know if the ImageView's parent is a RelativeLayout or a LinearLayout. Is there a way to tell this programmatically?

public class ResizeableImage extends ImageView {

View parent = null;

public ResizeableImage(Context context, AttributeSet attrs, int defaultStyle) {
    super(context, attrs, defaultStyle);
}

@Override
protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld)
{
    super.onSizeChanged(xNew, yNew, xOld, yOld);
    parent = (View) this.getParent();
    int parentHeight = parent.getHeight();
    int parentWidth = parent.getWidth();

    //parent.setMinimumHeight(yNew);
    //parent.setMinimumWidth(xNew);
    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) parent.getLayoutParams();
    params.height = yNew;
    params.width = xNew;
    parent.setLayoutParams(params);


}

}

In order to set the parent's new size (and for extensibility), I need to know whether it's a RelativeLayout, or any other kind.

Upvotes: 0

Views: 52

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006974

Call getParent() and do an instanceof check to see whether it is a certain type of interest (e.g., getParent() instanceof RelativeLayout).

Note that in this case, width and height are defined on ViewGroup.LayoutParams, the base class for all LayoutParams classes, so you could just cast to that and avoid tying yourself to RelativeLayout, etc.

Upvotes: 2

Related Questions