如何在Android中查看父级中的位置?

时间:2018-01-26 07:46:29

标签: android

我正在开发Android APP。我自定了View是HtMarkerView并覆盖了视图的onTouchEvent方法。我希望在其父母坐标中获得视图的位置。 视图的布局是ConstraintLayout。 我尝试了view.getTop,但它总是返回0.

这是布局xml

  <android.support.constraint.ConstraintLayout
    android:id="@+id/constraintLayoutScopeView"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:background="#FF353535"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toStartOf="@+id/constraintLayoutSubRightBar"
    app:layout_constraintStart_toEndOf="@+id/constraintLayoutLeftBar"
    app:layout_constraintTop_toBottomOf="@+id/constraintLayoutTopToolsBar">

    <com.hantek.ht6000api.Views.HtMarkerView
        android:id="@+id/chaLevelMarker"
        android:layout_width="70dp"
        android:layout_height="40dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        app:layout_constraintStart_toStartOf="parent"
        app:htMarkerColor="@color/colorCha"
        app:htMarkerRatio="2.8"
        app:htMarkerType="htMarkerTypeRight" />

</android.support.constraint.ConstraintLayout>

1 个答案:

答案 0 :(得分:0)

经过一番尝试后,我使用这个mehotd来获取视图在其父协调中的位置。

private Point getRelativePosition(View v) {
    int[] locationInScreen = new int[2]; // view's position in scrren
    int[] parentLocationInScreen = new int[2]; // parent view's position in screen
    v.getLocationOnScreen(locationInScreen);
    View parentView = (View)v.getParent();
    parentView.getLocationOnScreen(parentLocationInScreen);
    float relativeX = locationInScreen[0] - parentLocationInScreen[0];
    float relativeY = locationInScreen[1] - parentLocationInScreen[1];
    return new Point((int) relativeX, (int) relativeY);
}