gpt4 book ai didi

android - GridLayout 子项的 getLocationOnScreen

转载 作者:太空狗 更新时间:2023-10-29 15:34:54 26 4
gpt4 key购买 nike

我试图在 GridLayout 中获取 ImageView 的 x/y,但我的日志一直显示 X & Y: 0 0 有什么想法吗?

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/root" >

...

<GridLayout
android:id="@+id/gridLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:columnCount="3"
android:rowCount="5" >

...

<ImageView
android:id="@+id/fivetwo"
android:layout_width="75dp"
android:layout_height="75dp"
android:contentDescription="@string/gameboard"
android:gravity="center"
android:src="@drawable/tile"
android:layout_columnSpan="1"
android:layout_rowSpan="1" />

这里是java:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level);
....
ImageView temp = (ImageView) findViewById(R.id.fivetwo);
int originalPos[] = new int[2];
temp.getLocationOnScreen( originalPos );
Log.i(TAG, "X & Y: " + originalPos[0] + " " + originalPos[1]);

...

最佳答案

Remember:getX() and getY()return 0 if components are not drawn yet (in onCreate(){} ).


view 就绪后立即找出它的位置:

在布局中添加一个树观察器。这应该返回正确的位置。onCreate 在 subview 的布局完成之前被调用。所以宽度和高度还没有计算出来。获取高度和宽度。把它放在 onCreate 方法上

final ImageView temp = (ImageView) findViewById(R.id.fivetwo);
ViewTreeObserver vto = temp.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
temp.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int x = temp.getX();
int y = temp.getY();
Log.v(TAG, String.format("X:%d Y:%d",x,y);
}
});

关于android - GridLayout 子项的 getLocationOnScreen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19525945/

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