2017-01-05 105 views
0

我想知道圖像視圖的位置,但其始終返回0座標不是x座標或y座標。這裏是我的代碼爲什麼屏幕上的位置總是返回0?

ImageView credits = (ImageView) v.findViewById(R.id.credits); 
    int[] coor = {0,0}; 
    credits.getLocationOnScreen(coor); 
    x = coor[0]; 
    y = coor[1]; 

我已經使用了很多方法,如getTop()等,但仍以其返回0

任何人都知道爲什麼嗎?我是新來的機器人,所以我非常感謝任何答案。

回答

0

你在做onCreate方法嗎?

如果是的話,還爲時過早檢查getLocationOnScreen()中的onCreate()

這裏的解決方案:https://stackoverflow.com/a/13244091/5392383

+0

是的,我明白了。我把它放在onCreate()之前。非常感謝! –

0

您是否在onCreate()方法中使用此代碼?

經過快速搜索,我發現THIS POST

不久,它說onCreate()爲時過早getLocationOnScreen,當你的Activity獲得焦點時,你應該在方法onWindowFocusChanged()中使用它。

0
credits.post(new Runnable() { 
     @Override 
     public void run() { 
      int[] coor = {0,0}; 
      credits.getLocationOnScreen(coor); 
      x = coor[0]; 
      y = coor[1]; 
     } 
    }) 

嘗試這樣

0

請試試這個

@Override 
    protected void onResume() { 
     super.onResume(); 
     ImageView credits = (ImageView) v.findViewById(R.id.credits); 
     int[] coor = {0,0}; 
     credits.getLocationOnScreen(coor); 
     x = coor[0]; 
     y = coor[1]; 
    } 
相關問題