gpt4 book ai didi

android - 奇怪的 View.getHitRect() 行为

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:02:43 25 4
gpt4 key购买 nike

我有一个简单的布局:

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

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="animate"
android:text="animate" />

</LinearLayout>

在我的 Activity 中,我在更改按钮的 y 位置后打印 hit rect of button:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void animate(View view) {
printHitRect();
findViewById(R.id.button1).setY(50);
printHitRect();
}
private void printHitRect() {
Rect rect = new Rect();
findViewById(R.id.button1).getHitRect(rect);
Log.d(">>button1 hit rect", rect.flattenToString());
}
}

预期输出

button1 hit rect: 0 0 116 72

button1 hit rect: 0 50 116 122

实际输出

button1 hit rect: 0 0 116 72

button1 hit rect: -58 14 58 86

有人可以解释这个输出,我做错了什么还是一个错误?基本上,我在我的自定义 ViewGroup 中使用此 getHitRect() 来检测哪个 child 用户已触摸。有没有更好的方法让 child 在特定点,可能是像 getChildAt(x, y) 这样的函数?

我试过 setTranslateY(),而不是 setY()。我还使用了 NineOldAndroid 库以及内置的动画框架。如果我使用 findViewById(R.id.button1).animate().y(50) 而不是 setY(),可以看到相同的行为。

更新:

我最终使用现在可用的 nineoldandroid 库编写了实用程序方法:

private static void getHitRect(View v, Rect rect) {
rect.left = (int) com.nineoldandroids.view.ViewHelper.getX(v);
rect.top = (int) com.nineoldandroids.view.ViewHelper.getY(v);
rect.right = rect.left + v.getWidth();
rect.bottom = rect.top + v.getHeight();
}

最佳答案

getHitRect() 有一个错误,无法正确应用转换。我们在内部修复了这个错误,并将在下一个 Android 公开版本中提供修复。

关于android - 奇怪的 View.getHitRect() 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17750116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com