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>
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:
登录:
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位置一样吗?我能让他们变得不同吗?
为什么你期望的位置是不同的,在你修改它的代码中是否有任何地方? – alfasin
我期望位置不同,因为我在三个不同的视图上调用View.getY(),每个视图都在不同的Y位置。 – Pythogen