【问题标题】:How to get view position in window while this view is in a layout which is in another layout?当此视图位于另一个布局中的布局中时,如何获取窗口中的视图位置?
【发布时间】:2018-12-02 11:35:15
【问题描述】:

我试过这个(设置为按钮):

@Override
public boolean onTouch(View v, MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        lastTouchXonWindow = event.getX() + v.getX();
        lastTouchYonWindow = event.getY() + v.getY(); 
    }
    return false;
}

当视图在活动的唯一一个布局中时有效,但如果它在另一个布局中不起作用,因为 v.getX() 给我父布局中的 X 位置而不是窗户。

这是一个活动布局的例子:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">


<!-- Some Widgets ...-->

    <LinearLayout
        android:id="@+id/ChallengeLinearChoix12"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center">

        <Button
            android:id="@+id/ChallengeButtonChoix1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="01"
            style="@style/TresGrand"/>

        <Button
            android:id="@+id/ChallengeButtonChoix2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="02"
            style="@style/TresGrand"/>
    </LinearLayout>

</LinearLayout>

FurtherMore 我试过这个会产生错误“无法解析 getY() 方法”:

        lastTouchY =  event.getY() + v.getY() + v.getParent().getY();

【问题讨论】:

  • 使用 event.getRawX(), event.getRawY()。可以根据整个窗口获取触摸坐标。

标签: java android layout view widget


【解决方案1】:

.getRawX() 用于绝对触摸的位置(感谢 pistolcaffe),然后 .getLocationOnScreen() 用于绝对视图的位置

@Override
public boolean onTouch(View v, MotionEvent event) {
    int[] location = new int[2];
    layoutParent.getLocationOnScreen(location);
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        lastTouchX =  event.getRawX() - location[0];
        lastTouchY =  event.getRawY() - location[1];

        textAnimationScore.setText(""+location[1]);
    }
    return false;
}

我不得不在 Java Activity 中添加父布局,我很惊讶 v.getRootView().getLocationOnScreen(location) 给出 0 而不是 160。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多