我将MainActivity中的值设置为Fragment,但Fragment中的值变为0。 当我登录moveToLocation()时,纬度值为0,但是当我登录setLocation时,纬度值是正确的传递值。 这是为什么?
MainActivity
MapFragment mapFragment = new MapFragment();
mapFragment.setLocation(111, 222, "abcAddress");
片段
public class MapFragment extends Fragment {
private GoogleMap mMap;
private double mLatitude;
private double mLongitude;
private String mAddress;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
MapsInitializer.initialize(getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
Log.d("", "You must update Google Maps.");
getActivity().finish();
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mMap = ((SupportMapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
moveToLocation();
}
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.map_page, null);
}
public void setLocation(double latitude, double longitude, String address) {
mLatitude = latitude;
mLongitude = longitude;
mAddress = address;
}
protected void moveToLocation() {
CameraPosition location = new CameraPosition.Builder()
.target(new LatLng(mLatitude, mLongitude)).zoom(15.5f)
.bearing(0).tilt(25).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(location));
MarkerOptions marker = new MarkerOptions().position(new LatLng(mLatitude, mLongitude)).title(mAddress);
marker.snippet("Snippet");
mMap.addMarker(marker);
}
}
答案 0 :(得分:0)
您不应该创建MapFragment
的新实例。
要传递值,请在Argument中设置它们,同时在Transaction:
中添加它们Bundle bundle = new Bundle();
bundle.putDouble("lat", latitude);
bundle.putDouble("long", longitude);
bundle.putString("address", address);
myFragment.setArguments(bundle);
并获取onCreate()
中的值,如:
@Override
public View onCreate(Bundle savedInstanceState) {
Bundle mBundle = getArguments();
if (mBundle != null) {
String address = mBundle.getString("address");
// Call method
setLocation(mBundle.getDouble("lat"), mBundle.getDouble("long"), mBundle.getString("address"));
} else {
Toast.makeText(getActivity(), "Location Not Found", Toast.LENGTH_SHORT).show();
}
}
希望它有助于ツ