View.getY()没有返回正确的位置

问题描述:

我正在以编程方式将视图添加到垂直线性布局。所有的视图都是从同一个XML生成的。但是,如果我在每个视图上调用View.getY(),它将返回相同的y值。为什么会发生?我怎样才能让它返回正确的Y值?View.getY()没有返回正确的位置

要充气XML代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="wrap_content"> 

    <RelativeLayout 
     android:layout_width="50dp" 
     android:layout_height="50dp" 
     android:layout_margin="50dp" 
     android:id="@+id/myView" 
     android:background="@color/colorAccent"> 

    </RelativeLayout> 
</RelativeLayout> 

的要充气XML的预览: enter image description here

Java代码:

public class MainActivity extends Activity { 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     final LinearLayout host = ((LinearLayout) findViewById(R.id.host)); //Linear Layout to hold the views, orientation = vertical 

     //Creating the views and adding them to a list 
     final ArrayList<MyObject> myObjects = new ArrayList<>(); 
     for (int i = 0; i < 3; i++) { 
      myObjects.add(MyObject.createNewObject(this, host)); 
     } 

     //Waiting for the screen to be drawn 
     host.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 
      @Override 
      public void onGlobalLayout() { 
       //get the Y position of each pink box 
       for (MyObject m : myObjects) { 
        Log.v("MYOBJECT", "Y pos: " + String.valueOf(m.myPartView.getY())); 
       } 
       host.getViewTreeObserver().removeOnGlobalLayoutListener(this); 
      } 
     }); 
    } 
} 

class MyObject { 
    View myWholeView; 
    View myPartView; 

    private MyObject(View myWholeView, View myPartView) { 
     this.myWholeView = myWholeView; 
     this.myPartView = myPartView; 
    } 

    public static MyObject createNewObject(Context context, LinearLayout host) { 
     View v = LayoutInflater.from(context).inflate(R.layout.layout, host, true); //Inflating the XML Layout 
     View other = v.findViewById(R.id.myView); //This is the little pink box 
     return new MyObject(v, other); 
    } 
} 

我跑的代码,结果是这样的:

正确生成的XML:

enter image description here

登录:

04-07 15:35:39.811 20695-20695/com.pythogen.tester V/MYOBJECT: Y pos: 150.0 
04-07 15:35:39.811 20695-20695/com.pythogen.tester V/MYOBJECT: Y pos: 150.0 
04-07 15:35:39.811 20695-20695/com.pythogen.tester V/MYOBJECT: Y pos: 150.0 

为什么所有的Y位置一样吗?我能让他们变得不同吗?

+0

为什么你期望的位置是不同的,在你修改它的代码中是否有任何地方? – alfasin

+0

我期望位置不同,因为我在三个不同的视图上调用View.getY(),每个视图都在不同的Y位置。 – Pythogen

你得到的价值是相对于它的父母,这就是为什么你总是得到相同的价值。如果您想在屏幕上显示位置,您可以使用View.getLocationOnScreen()

+1

根据文档:'getY() - 此视图的可视y位置,以像素为单位https://developer.android.com/reference/android/view/View.html#getY() 因此很自然地,我认为'getY()'会返回视觉位置,'getTop()'返回相对于父对象的位置。谢谢你的澄清。 – Pythogen

+0

@Pythogen如果这个答案解决了你的问题 - 请标记为“接受” – alfasin