Home » Android » android – Methods to get position of view returns 0

android – Methods to get position of view returns 0

Posted by: admin June 15, 2020 Leave a comment

Questions:

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.

How to&Answers:

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.