我有一个简单的布局:
<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();
}