Как использовать SupportMapFragment внутри фрагмента?
Я знаю, что возникла проблема с использованием вложенного фрагмента. Но мое приложение было разработано для работы на фрагментах, и если я буду использовать активность для карты, мои функции кастинга будут иметь ошибку.
Я хотел бы попросить у вас помощи о том, как этого добиться. Я искал в Интернете, но не нашел лучшего решения.
Я пробовал этот код:
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) myFragmentActivity.getSupportFragmentManager().findFragmentById(R.id.map_con))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setMyLocationEnabled(true);
}
}
}
это даст мне повторяющуюся ошибку из-за R.id.map_con - фрагмент внутри моего фрагмента.
Итак, я ищу работу, на этот раз R.id.map_con - это макет кадра, и во время выполнения я создал для него SupportMapFragment.
SupportMapFragment mSupportMapFragment = new SupportMapFragment();
myFragmentActivity.getSupportFragmentManager().beginTransaction()
.replace(R.id.map_con, mSupportMapFragment).commit();
хотя это не дает мне дубликат при каждом закрытии и открытии фрагмента. но моя ошибка в том, что mSupportMapFragment.getMap всегда имеет значение null. Я не понимаю, почему его null?
mMap = mSupportMapFragment.newInstance().getMap();
if (mMap != null){
Log.e("ReportFragment","mMap is not empty");
}else{
Log.e("ReportFragment","mMap is empty");
}
Я был бы очень признателен за любые материалы от вас, ребята, или у вас есть другая работа, но все еще в этом процессе, т.е. фрагмент внутри фрагмента
Спасибо
chkm8
Ответы
Ответ 1
Я просто встретил свою удачу, создав этот пост, я нашел то, что искал Im.
Я использовал это:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_location, container, false);
mMapFragment = new SupportMapFragment() {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mMap = mMapFragment.getMap();
if (mMap != null) {
setupMap();
}
}
};
getChildFragmentManager().beginTransaction().add(R.id.framelayout_location_container, mMapFragment).commit();
return v;
}
Кредит на Старый пост
Ответ 2
getMap()
устарел
Код должен быть примерно таким же, как в Fragment
:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_location, container, false);
mMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mMapFragment.getMapAsync(this);
return v;
}
Ответ 3
Я использовал его в заданном порядке, и он отлично работает.
Он также работает с getChildFragmentManager()
MapyFragment
public class MapyFragment extends Fragment implements OnMapReadyCallback {
private Context mContext;
private SupportMapFragment supportMapFragment;
private GoogleMap map;
private MarkerOptions currentPositionMarker = null;
private Marker currentLocationMarker;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mContext = getActivity();
return inflater.inflate(R.layout.fragment_mapy, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mContext = getActivity();
FragmentManager fm = getActivity().getSupportFragmentManager();/// getChildFragmentManager();
supportMapFragment = (SupportMapFragment) fm.findFragmentById(R.id.map_container);
if (supportMapFragment == null) {
supportMapFragment = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.map_container, supportMapFragment).commit();
}
supportMapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
map.setMyLocationEnabled(true);
map.animateCamera(CameraUpdateFactory.zoomTo(15));
/*map.setOnMapLongClickListener(MapyFragment.this);
map.setOnMapClickListener(MapFragment.this);*/
}
public void updateCurrentLocationMarker(Location currentLatLng){
if(map != null){
LatLng latLng = new LatLng(currentLatLng.getLatitude(),currentLatLng.getLongitude());
if(currentPositionMarker == null){
currentPositionMarker = new MarkerOptions();
currentPositionMarker.position(latLng)
.title("My Location").
icon(BitmapDescriptorFactory.fromResource(R.drawable.start_blue));
currentLocationMarker = map.addMarker(currentPositionMarker);
}
if(currentLocationMarker != null)
currentLocationMarker.setPosition(latLng);
///currentPositionMarker.position(latLng);
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
}
и fragment_mapy.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="@+id/map_container"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
map:uiZoomControls="true" />