Can someone give me an example of how to get the center coordinates of the current displayed screen? I would like my objects to always be relative to the center coordinates of the active view.
Asked
Active
Viewed 1.5k times
11
-
Do you want coordinates or why can't you use center gravity? – OneCricketeer Jun 08 '16 at 16:46
-
@cricket_007 I'm open to any suggestions, I am new to android app development. I have an iOS app that does it, but I'm interested in the least complex equivalent for android. – 1QuickQuestion Jun 08 '16 at 17:15
-
Assuming you just want to center a view, see here http://stackoverflow.com/questions/1499258/how-to-center-a-view-inside-of-an-android-layout – OneCricketeer Jun 08 '16 at 17:17
-
@cricket_007 I really want the coordinate. I am moving an object about the x-axis; so I want to keep it within a certain range +/-[some value] of the screen center x-coordinate. – 1QuickQuestion Jun 08 '16 at 17:34
-
2[Get the screen dimensions](http://stackoverflow.com/questions/6520718/how-to-get-screen-width-and-height) and divide by 2, then? – OneCricketeer Jun 08 '16 at 17:38
-
try this answer http://stackoverflow.com/a/18304520/3678308 – Muhammad Waleed Jun 08 '16 at 17:47
-
@cricket_007 Your solution worked, do you want to post it as an answer so I can accept it? Thanks a lot! – 1QuickQuestion Jun 09 '16 at 14:05
3 Answers
12
You can try with DisplayMetrics
to achieve your solution
int mWidth= this.getResources().getDisplayMetrics().widthPixels;
int mHeight= this.getResources().getDisplayMetrics().heightPixels;
-
-
1@Gupta , one simple solution for that would setting the activity to never resize with keyboard (in the manifest) – Nasib Nov 19 '19 at 07:09
1
Here is how I resolved the issue. As a background, I have a button that once the user moves the map to the desired location (cross hairs showing the centre of map) they can tap the button and a marker appears in the centre of the map.
findViewById(R.id.addMarker).setOnClickListener(
new View.OnClickListener(){
@Override
public void onClick(View view) {
if(myMap != null){
double myLat = myMap.getCameraPosition().target.latitude;
double myLng = myMap.getCameraPosition().target.longitude;
LatLng markerPoint = new LatLng(myLat, myLng);
myMap.addMarker(new MarkerOptions().position(markerPoint)).setTitle("new marker");
}
}
}
);

timv
- 3,346
- 4
- 34
- 43
1
int cx =screenHeight = displaymetrics.heightPixels;
int cy = screenWidth = displaymetrics.widthPixels;
float finalRadius = (float) Math.sqrt(cx * cx + cy * cy);
float is the center if the object

Waqar Khan
- 42
- 6