Reputation: 1421
I am developing an android lock screen app. I got the idea from another thread to check the coordinates of where the finger has pressed down against to the coordinates of the imagebutton that I have set up.
I am trying to get the coordinates of the imagebutton using the .getTop()
and .getLeft()
but both are returning 0.0 (as they are floats, not int).
why is this? I am new to android development, so sorry if I am missing something obvious.
Also, I read somewhere that the .getTop()
won't work after the setContentView(R.layout.layoutname)
but if I put it above setContentView(...)
then the app crashes.
Is there another way to get the coordinates of the imagebutton, or would it be better/easier to get the coordinates and bounds of the table cell ? How would I do that?
Thanks in advance :)
Upvotes: 6
Views: 8073
Reputation: 1045
I came across this problem when calling .getTop()
from within onCreateView()
or onViewCreated()
.
In this state, the Views were not yet drawn and hence the actual coordinates are not known yet.
One workaround is to make the values be read in the following UI cycle using a handler:
int buttonTop;
int buttonLeft;
// ...
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
final ImageButton imageButton = view.findViewById(R.id.your_imagebutton_id);
new Handler(Looper.getMainLooper()).post(() -> {
buttonTop = imageButton.getTop();
buttonLeft = imageButton.getLeft();
});
}
Upvotes: 2
Reputation: 29436
You need your view added to a layout and displayed (At least one layout pass and measure pass must have run.). Also, the co-ordinates so obtained are relative to view's immediate parent.
It is possible to retrieve the location of a view by invoking the methods getLeft() and getTop(). The former returns the left, or X, coordinate of the rectangle representing the view. The latter returns the top, or Y, coordinate of the rectangle representing the view. These methods both return the location of the view relative to its parent. For instance, when getLeft() returns 20, that means the view is located 20 pixels to the right of the left edge of its direct parent.
Upvotes: 6
Reputation: 8702
This should do the job ;)
// Your view
ImageView image = (ImageView) findViewById(R.id.image);
Rect rect = new Rect();
image;getLocalVisibleRect(rect);
Log.d("WIDTH :",String.valueOf(rect.width()));
Log.d("HEIGHT :",String.valueOf(rect.height()));
Log.d("left :",String.valueOf(rect.left));
Log.d("right :",String.valueOf(rect.right));
Log.d("top :",String.valueOf(rect.top));
Log.d("bottom :",String.valueOf(rect.bottom));`
Upvotes: -1
Reputation: 775
imagebutton.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
try this before imagebutton.getTop()?
Upvotes: 2