12

我有一个简单的布局:

<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>

在我的活动中,我在更改其y位置后打印按钮的按钮:

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 点击矩形:0 0 116 72

button1 点击矩形:0 50 116 122

实际输出

button1 点击矩形:0 0 116 72

button1 击中矩形:-58 14 58 86

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

而不是setY(),我试过了setTranslateY()。我还使用了 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();
}
4

3 回答 3

11

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

于 2013-07-19T17:17:11.960 回答
2

你可以通过这种方式直接命中:

public Rect getHitRect(View child){
   Rect frame = new Rect();
   frame.left = child.getLeft();
   frame.right = child.getRight();
   frame.top = child.getTop();
   frame.bottom = child.getBottom();
   return frame;
}
于 2013-07-29T02:58:16.553 回答
1

这是一个不依赖于 NineOldAndroids 的解决方案。

如果您遵循 NineOldAndroids 代码路径的代码路径,您最终会在后蜂窝设备上到达这里:Github

private static void getHitRect(View v, Rect rect) {
    rect.left = (int) (v.getLeft() + v.getTranslationX());
    rect.top = (int) (v.getTop() + v.getTranslationY());
    rect.right = rect.left + v.getWidth();
    rect.bottom = rect.top + v.getHeight();
}
于 2014-08-27T20:49:59.587 回答