如何以像素为单位获取视图之间的距离?

Ket*_*tan 4 java android relativelayout imageview

如下图所示.我有一个relative layout.我有我ImageView的相同,我需要在视图开始和这个ImageView之间获得像素差距.我的活动如下.请指教.我试过各种各样的方法,topY()但找不到解决办法.

在pixcel找到距离

    <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>
Run Code Online (Sandbox Code Playgroud)

Dou*_*ior 7

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

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

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

float distance = Math.abs(oneRect.bottom - otherRect.top);
Run Code Online (Sandbox Code Playgroud)

util方法:

public static RectF calculeRectOnScreen(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());
}
Run Code Online (Sandbox Code Playgroud)

在某些情况下,您需要替换view.getLocationOnScreento view.getLocationInWindow.