我遇到地图碎片问题。错误消息是无法从Fragment转换为MapFragment 。我尝试与extends FragmentActivity
一起更改为GoogleMap map = ((SupportMapFragment) getSupportFragmentManager()
,但这会导致我的onCreateView
代码行出现问题。
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class Fragment01 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_01, container, false);
// Get a handle to the Map Fragment
GoogleMap map = ((MapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
LatLng sydney = new LatLng(-33.867, 151.206);
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));
map.addMarker(new MarkerOptions()
.title("Sydney")
.snippet("The most populous city in Australia.")
.position(sydney));
}
}
答案 0 :(得分:5)
替换
getFragmentManager
带
getSupportFragmentManager
getFragmentManager
会返回androids api fragment
(可从v11 +获得)类的实例,但您已导入android.support.v4.app.Fragment
。
因此,请致电getSupportFragmentManager
或更改输入。
getSupportFragmentManager仅在FragmentActivity
类中可用。
因此,您需要先将此片段放入FragmentActivity
(范围FragmentActivity
而不是Activity
),然后在onActivityCreated
片段方法中获取活动参考并调用{ {1}}。 e.g。
getSupportFragmentManager
for ref。: How can I access getSupportFragmentManager() in a fragment?
答案 1 :(得分:4)
尝试这些代码行,它们可能会对您有所帮助:
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
supportMapFragment = (SupportMapFragment) fragmentManager.findFragmentById(R.id.map);
Google_Map = supportMapFragment.getMap();