使用startActivityForResult()
爲了打開MapsActivity,然後在谷歌地圖上使用點擊監聽器來讓用戶選擇一個點。
這是一個簡單的例子。
首先,MainActivity,這在點擊一個按鈕與緯度/用戶選擇在MapsActivity點的經度開闢了MapsActivity,並顯示出吐司:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_two);
Button button = (Button) findViewById(R.id.button_pick_point);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
pickPointOnMap();
}
});
}
static final int PICK_MAP_POINT_REQUEST = 999; // The request code
private void pickPointOnMap() {
Intent pickPointIntent = new Intent(this, MapsActivity.class);
startActivityForResult(pickPointIntent, PICK_MAP_POINT_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_MAP_POINT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
LatLng latLng = (LatLng) data.getParcelableExtra("picked_point");
Toast.makeText(this, "Point Chosen: " + latLng.latitude + " " + latLng.longitude, Toast.LENGTH_LONG).show();
}
}
}
}
然後,MapsActivity,它使用GoogleMap.OnMapClickListener
爲了獲得用戶選擇的點的緯度/經度,並將數據傳回給MainActivity。請注意,由於LatLng對象實現了Parcelable接口,因此它可以作爲額外的對象傳遞。
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
Intent returnIntent = new Intent();
returnIntent.putExtra("picked_point",latLng);
setResult(Activity.RESULT_OK,returnIntent);
finish();
}
});
}
}