查找父视图的高度

时间:2015-02-09 06:04:01

标签: android imageview android-custom-view

我正在创建自定义imageview,我正在尝试查找父级的高度。我所知道的关于父母的唯一细节是它可能会滚动。我需要父母身高的原因是因为我想弄清楚imageview在屏幕上的位置。我已经制作了一个方程式,可以准确计算它的位置,但它只有在我手动输入父级高度时才有效。有没有办法检索这些信息,还是有其他方法可以在每次更改时在屏幕上显示我的imageview的位置?

1 个答案:

答案 0 :(得分:2)

试试这种方式

public class MyImageView extends ImageView {


    int parentHeight;
    int parentWidth;

    public MyImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

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

    public MyImageView(Context context) {
        super(context);
    }





    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        if(((View)this.getParent()).getMeasuredWidth()!=0){
            parentHeight = ((View)this.getParent()).getMeasuredHeight();
            parentWidth = ((View)this.getParent()).getMeasuredWidth();
        }

    }
}