in ManActivity onCreate() I instantiated a new View and added it via layout.addView to the activity. If i try getX() or getY() for that view I always get 0.0.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout main = (RelativeLayout)findViewById(R.id.main);
RelativeLayout.LayoutParams squarePosition = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
GameToken square1 = new GameToken(this,GameToken.SQUARE, fieldHeight,fieldWidth);
squarePosition.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
squarePosition.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
main.addView(square1, squarePosition);
System.out.println(square1.getX()); //Prints '0.0'
System.out.println(square1.getY()); //Prints '0.0'
ViewGroup
s such asRelativeLayout
do not layout their children immediately, and thus your View does not yet know where it will lie on screen. You need to wait for theRelativeLayout
to complete a layout pass before that can happen.You can listen for global layout events like so:
Another option is to use
post(Runnable action)
method:This will cause the Runnable to be executed after the other pending tasks (such as laying out) are finished.
Move your calls to getX() and getY() into onWindowFocusChanged() callback. As the official guide says, that's the best way to know if the activity is visible to the user. Looking at your code, you can put your square into member variables in order to be able to use it with both callbacks.
Try this:
The general rule is that you can't retrieve positions information from your layout within onCreate(), because you are just creating it and android still have to elaborate them.
You can give a chance to onResume() callback too, but for me it didn't work.