Reputation: 657
im writing my first android app (im not new to java). heres my problem: i use an ImageView to show a graphic. I would like to write a method thas is called when the ImageView is touched and gets the touch coordinates as parameters.
Here is my current solution:
img.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent e) {
clickfield((int) e.getX(), (int) e.getY());
toast.setText((int) e.getX() + ", " + (int) e.getY());
toast.show();
return true;
}
});
...
public void clickfield(int x, int y) {
...
}
I have two problems with this: At first, the coordinates that it returns are not the real coordinates on the phone. my vm has a resolution of 480 x 800 pixels. As the ImageView is 480*480 pixels large, the y value should be between 0 and 480. The actaual value is between 0 and 320.This could be solved by multiplying it by 1.5, but this doesnt make sense to me.
The second problem is that the 480 * 480 Bitmap which is the content of the ImageView appears in the middle of the screen. I would prefer to display it at the top, especially beacause the the above code detects something like 0, 72 if i touch the up left corner of the image instead of 0, 0. Which property of the image view do I have to change?
If there is any reference/tutorial that answers my question, it would suffice if you post a link.
my xml layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:src="@drawable/icon"
android:id="@+id/ImgTest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:layout_gravity="top">
</ImageView>
</LinearLayout>
Upvotes: 0
Views: 5162
Reputation:
The coordinates you get relate to the the (Image)View to which the listener is attached. Your image gets scaled to fit that view. So your view is 320px wide or high. If you want to get the actual pixel coordinate, you have to calculate that from the Views width/height and the image ones. Almost like you did, but with a dynamic factor, since you will get different ones for every screen size.
The positioning of your actual image is also related to that. If the image is bigger or smaller than your view, it gets resized while maintaining its aspect ratio. If this doesn't match your screens aspect ratio, you will get some borders. To position the image on top of your layout, you should let the ImageView
automatically resize its height to the required size of the image. You can do that via setting the android:layout_height
to wrap_content
in your layout file (inside the ImageView
tag). If it still stays in the middle, you probably have to also adjust your outer layouts gravity. See android:gravity
(what you want here is top
).
Upvotes: 1