Methods to get position of view returns 0

拈花ヽ惹草 提交于 2019-12-12 08:33:06

问题


This question has been asked several times, but everyone gives the reason for why this occurs (i.e. calculation occurs before the layout is laid). But I need the solution for this. I tried getBottom();, getTop();, getLocationOnScreen(int[] location);. But all returns the value Zero (0). I even tried giving these in onStart();, to give time for layout to be laid, but no luck. Here is my code:

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

Layout 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>

Again, I apologize for repeating the question. Thanks in advance.


回答1:


You put the 'measuring' in the onWindowFocusChanged()-method.
As the documentation states:

This is the best indicator of whether this activity is visible to the user.

You could also put it in the onResume() which is the last step before the application is completely on screen and active, however:

Keep in mind that onResume is not the best indicator that your activity is visible to the user; a system window such as the keyguard may be in front. Use onWindowFocusChanged(boolean) to know for certain that your activity is visible to the user (for example, to resume a game).

If the window/view has not yet been displayed there is no guarantee that it has its measurements, thus the previous method would be better.



来源:https://stackoverflow.com/questions/8879504/methods-to-get-position-of-view-returns-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!