繁体   English   中英

查看 getX() 和 getY() 添加到 Activity 后返回 0.0

[英]View getX() and getY() return 0.0 after they have been added to the Activity

在 MainActivity onCreate() 中,我实例化了一个新视图并通过 layout.addView 添加到活动中。 如果我为该视图尝试 getX() 或 getY() ,我总是得到 0.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 如RelativeLayout不会立即布局他们的孩子,因此您的 View 还不知道它会在屏幕上的位置。 在此之前,您需要等待RelativeLayout完成布局传递。

您可以像这样侦听全局布局事件:

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);
        }
    });

另一种选择是使用post(Runnable action)方法:

view.post(new Runnable() {
    @Override
    public void run() {
        System.out.println(view.getX());
        System.out.println(view.getY());
    }
});

这将导致 Runnable 在其他待处理任务(例如布局)完成后执行。

将您对 getX() 和 getY() 的调用移动到onWindowFocusChanged()回调中。 正如官方指南所说,这是了解活动是否对用户可见的最佳方式。 查看您的代码,您可以将您的方块放入成员变量中,以便能够在两个回调中使用它。

尝试这个:

    GameToken mSquare1 = new GameToken(this,GameToken.SQUARE, fieldHeight,fieldWidth);

    ...
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {

          super.onWindowFocusChanged(hasFocus);

          if(hasFocus) {
             System.out.println(mSquare1.getX());
             System.out.println(mSquare1.getY());
          }
    } 

一般规则是您不能在 onCreate() 中从您的布局中检索位置信息,因为您只是在创建它而 android 仍然需要详细说明它们。

您也可以给 onResume() 回调机会,但对我来说它不起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM