Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

android - View getX() and getY() return 0.0 after they have been added to the Activity

In MainActivity 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'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

ViewGroups such as RelativeLayout 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 the RelativeLayout to complete a layout pass before that can happen.

You can listen for global layout events like so:

view.getViewTreeObserver().addOnGlobalLayoutListener(
    new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            // Layout has happened here.

            // Don't forget to remove your listener when you are done with it.
            view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
    });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...