getRight、getLeft、getTop 返回零

10

我正在使用以下代码。但是所有方法都返回零值。我知道要获取视图的坐标,我们的视图应该被绘制。这就是为什么我在onResume方法中使用该代码,但仍然无法工作。有什么想法吗?

 @Override
public void onResume(){
    super.onResume();
    System.out.println("Onresume"); 
    System.out.println("tab1 - left" + btn_Tab7 .getLeft());
    System.out.println("tab1 - Top" + btn_Tab7.getTop());
    System.out.println("tab1 - right" + btn_Tab7.getRight());
    System.out.println("tab1 - bottom" + btn_Tab7.getBottom()); 
}

使用ViewTreeObserver在视图绘制完成后获得通知。 - WarrenFaith
谢谢你的回答。但是根据生命周期文档,当我们进入OnResume方法时,所有视图已经绘制完成。为什么我需要使用ViewTreeObserver类来完成这个任务呢?我已经使用了这个类来完成我的任务,但我想澄清我的概念,而不仅仅是完成任务。 - user1154390
1个回答

9
onResume中调用getLeft、getRight等方法还为时过早,应该在onWindowFocusChanged中调用。
@Override
public void onWindowFocusChanged (boolean hasFocus){
    super.onWindowFocusChanged(hasFocus);
    if(hasFocus){
        System.out.println("onWindowFocusChanged"); 
        System.out.println("tab1 - left" + btn_Tab7 .getLeft());
        System.out.println("tab1 - Top" + btn_Tab7.getTop());
        System.out.println("tab1 - right" + btn_Tab7.getRight());
        System.out.println("tab1 - bottom" + btn_Tab7.getBottom());
    }
}

从onResume的文档中可以了解到:

请注意,onResume并不是判断你的activity是否对用户可见的最佳指标;系统窗口如锁屏可能会在其前面。使用onWindowFocusChanged(boolean)来确保你的activity对用户可见(例如,恢复游戏)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接