获取文本视图和图像视图相对于屏幕顶部的结束位置



我有一个位图,它下面是一条时间线。

例如,考虑图的右侧布局。

所有底部时间线(1、2、3…)从顶部起都在同一高度。

时间线是一个文本视图,具有固定的布局高度和宽度,因为它是在xml中定义的类似时间线1被定义为:

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/HView"
android:layout_marginLeft="18dp"
android:layout_marginTop="345dp"
android:textSize="14sp"
android:text="1"
android:textColor="#000000" />

但是,位图的高度和宽度可以随着程序的执行而变化。

因此,在某些情况下,位图的高度会增加到与时间线重叠的程度。换句话说,位图的垂直位置相对于时间线的垂直位置增加。

我想获得:

1)位图相对于屏幕顶部的结束垂直位置。

2)时间线相对于屏幕顶部的结束垂直位置。

我试着做了以下事情:

TextView bottomTimeLine = (TextView) view.findViewById(R.id.textView1);
bottomTimeLine.getHeight(); //returns 0.
bottomTimeLine.getBottom(); //returns 0.
ImageView img = new ImageView(getActivity());
img.setImageDrawable(getResources().getDrawable(R.drawable.disp_bg));
img.getHeight(); //returns 0.
img.getBottom(); //returns 0.

从代码中可以看出,getHeight()getBottom()这两个方法都将height返回为0。

如何获得两者相对于单元格显示顶部的高度(视图结束位置)?

希望这能帮助

@覆盖

protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec){super.onMeasure(widthMeasureSpec,heightMeasureSpec);

int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
this.setMeasuredDimension(
        parentWidth / 2, parentHeight);

}

这就是它的实现方式:

final TextView bottomTimeLine = (TextView) view.findViewById(R.id.textView1);
 final int[] timelineCoord = new int[2]; 
 final int[] imgCoord = new int[2]; 

ViewTreeObserver vto = bottomTimeLine.getViewTreeObserver();
 vto.addOnGlobalLayoutListener((new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {

        bottomTimeLine.getLocationOnScreen(timelineCoord);
    Log.d(" bottomTimeLine H ", ""+timelineCoord[1]);
    timelineHeight = timelineCoord[1];
    }
}));

ViewTreeObserver vt1 = img.getViewTreeObserver();
vt1.addOnGlobalLayoutListener((new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {

        img.getLocationOnScreen(imgCoord);
        imgHeight = imgCoord[1] + img.getHeight();
    Log.d("Img H ", ""+imgHeight);
if(imgHeight < timelineHeight)
{
int heightDiff = imgHeight - timelineHeight ;
heightDiff = heightDiff + 3;
img.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, heightDiff));
}
    }
}));

最新更新