我正在以编程方式将视图添加到垂直linearlayout。所有视图都是从相同的XML生成的。但是如果我在每个视图上调用View.getY(),它将返回相同的y值。为什么会这样?如何让它返回正确的Y值?
成为膨胀的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位置都一样?我可以让他们与众不同吗?
答案 0 :(得分:2)
您获得的价值与其父母相关,这就是为什么您总能得到相同的价值。如果您想在屏幕上显示该位置,可以使用View.getLocationOnScreen()
。