如何在像素中获取视图之间的距离?

10
如下图所示。我有一个相对布局。ImageView与之相同,我需要获得视图开始和此ImageView之间的像素差距。 我的活动如下,请建议。我尝试了各种方法,比如topY()但是没有找到解决方案。
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <LinearLayout
        android:id="@+id/main_ruler_linear_layout"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:orientation="horizontal" 
        >        
        </LinearLayout>

    <ImageView 
        android:id="@+id/line_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/line"/>

    <EditText
        android:id="@+id/txtRulerCenterPosition"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/main_ruler_linear_layout"
        android:layout_marginRight="17dp"
        android:layout_marginTop="16dp"
        android:ems="10" 
        android:textSize="5dp"
        android:focusable="false"/>

</RelativeLayout>
2个回答

14

计算一个视图底部和另一个视图顶部之间的距离:

View oneView = ...;
View otherView = ...;

RectF oneRect = calculateRectOnScreen(oneView);
RectF otherRect = calculateRectOnScreen(otherView);

float distance = Math.abs(oneRect.bottom - otherRect.top);

这是一个实用方法:

public static RectF calculateRectOnScreen(View view) {
    int[] location = new int[2];
    view.getLocationOnScreen(location);
    return new RectF(location[0], location[1], location[0] + view.getMeasuredWidth(), location[1] + view.getMeasuredHeight());
}

在某些情况下,需要将view.getLocationOnScreen替换为view.getLocationInWindow


@Douglass,距离的度量单位是什么?像素、sp、dp...谢谢。 - RonTLV
该单位与view.getMeasuredWidth()相同,即DP。 - Douglas Nassif Roma Junior

2
如果两个视图在视图层次结构中处于同一级别,则可以使用以下方法来确定它们之间的垂直距离(以像素为单位)。
public static int getDistanceBetweenViews(View firstView, View secondView) {
        int[] firstPosition = new int[2];
        int[] secondPosition = new int[2];

        firstView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        firstView.getLocationOnScreen(firstPosition);
        secondView.getLocationOnScreen(secondPosition);

        int b = firstView.getMeasuredHeight() + firstPosition[1];
        int t = secondPosition[1];
        return Math.abs(b-t);
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接