I hope I'm missing something ridiculously obvious here. I have an activity with an imageView and a textView in a Relative Layout. Obviously, the imageView will change position on the screen based on the size of the screen, so I'm trying to get the Xposition at which the imageView starts. getX() seems to be the thing I'm looking for. However, when I call it, the value returned is always 0.0.
At first I had it in the OnCreate method, then I researched and found that views aren't finished being created during the OnCreate method and may not exist. So one of the workarounds I found was to use onWindowFocusChanged (Boolean hasFocus) and call my dimensions in there. However, this isn't working either. When I debug the code and step into the lines, the getX() line is executing and returning 0.0. Shouldn't the views have already been created by the time the code in the onWindowFocusChanged method runs?
Here's my code:
@Override
public void onWindowFocusChanged (Boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
ImageView myImage = findViewById(R.id.image1);
TextView tv1 = findViewById(R.id.textView1);
RelativeLayout.LayoutParams layoutparams;
layoutparams = (RelativeLayout.LayoutParams) myImage.getLayoutParams();
myImage.setLayoutParams(layoutparams);
float image_start_pos = myImage.getX(); // <- this line returns 0.0
...
}
}
I also tried using ViewTreeObserver as detailed here, but that also returned 0.0. What am I doing wrong, or is there another, better method to use that is executed only after the activity is fully rendered?