how to get the pointer/cursor location in android

2019-02-19 21:16发布

问题:

In Android I would like to get/return the cursor location (latitude and longitude) when I click anywhere on the screen.

回答1:

I don't know for what you want to get latitude and longitude but I am sure you can get the position of the coordinates X and Y when a user touch the screen.

Implement OnTouchListener in your Activity and set the Listener for your View using the setOnTouchListener() method.

Now you can override the onTouch() method in your Activity.

@Override
public boolean onTouch(View view, MotionEvent event) {
    int x = (int) event.getX();       
    int y = (int) event.getY();
    return false;
}

See I have written a sample snippet for you:

    public class OnTouchDemo extends Activity implements OnTouchListener {

    private TextView tView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tView = (TextView) findViewById(R.id.txtView1);
        tView.setOnTouchListener(this);
    }

    @Override
    public boolean onTouch(View view, MotionEvent event) {
        int x = (int) event.getX();
        int y = (int) event.getY();

        Log.v("OnTouchDemo", "X==" + String.valueOf(x) + " Y==" + String.valueOf(y));

        return false;
    }
}


回答2:

For a location x,y on your MapView ,

MapView    map    = (MapView) findViewById(R.id.youmapview);
Projection proj   = map.getProjection();
GeoPoint   latlon = proj.fromPixels(x, y);