2012-01-16 92 views
8

此问题已被多次询问,但每个人都给出了发生这种情况的原因(即计算在布局之前发生)。但我需要这个解决方案。我试过getBottom();,getTop();,getLocationOnScreen(int[] location);。但是全部返回值零(0)。我甚至尝试在onStart();中给予这些,给布局铺平了时间,但没有运气。 这里是我的代码:获取视图位置的方法返回0

TextView tv; 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    tv = (TextView) findViewById(R.id.textView1); 
    Log.d("getBottom :", Integer.toString(tv.getBottom())); 
    Log.d("gettop  :", Integer.toString(tv.getTop())); 

    int[] location = new int[2]; 
    tv.getLocationOnScreen(location); 
    Log.d("getlocationonscreen values :", Integer.toString(location[0])+" "+Integer.toString(location[1])); 
} 
@Override 
protected void onStart() { 
    Log.d("getBottom in onStart :", Integer.toString(tv.getBottom())); 
    Log.d("gettop in onStart :", Integer.toString(tv.getTop())); 

    int[] location = new int[2]; 
    tv.getLocationOnScreen(location); 
    Log.d("getlocationonscreen in onStart :", Integer.toString(location[0])+" "+Integer.toString(location[1])); 
    super.onStart(); 
} 

布局XML:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" > 

<TextView 
    android:id="@+id/textView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentTop="true" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="156dp" 
    android:text="Medium Text" 
    android:textAppearance="?android:attr/textAppearanceMedium" /> 

</RelativeLayout> 

同样,我对重复的问题表示歉意。提前致谢。

+0

请问您能解释一下您的具体问题。上面的代码中会出现什么问题。 – 2012-01-16 11:45:26

回答

13

您将'测量'放在onWindowFocusChanged()-方法中。
由于文档状态:

这是该活动是否对用户可见的最佳指标。

你也可以把它放在onResume()这是应用程序之前的最后一步完全是在屏幕上活跃,但是:

记住的onResume是不是最好的指标,你的活动对用户可见;系统窗口(如键盘)可能在前面。使用onWindowFocusChanged(boolean)可以确定您的活动对用户是可见的(例如,恢复游戏)。

如果尚未显示窗口/视图,则不能保证它具有其测量值,因此以前的方法会更好。