Android [SupportMapFragment] 方法 findViewById(int) 未定义类型


public class PlaceMapsFragment extends SupportMapFragment {
    private GoogleMap mMap;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View v = inflater.inflate(R.layout.fragment_place_maps, container,
                false);

        setUpMapIfNeeded();
        return v;
    }
    private void setUpMapIfNeeded() {
        if (mMap == null) {
            mMap = ((MapView) findViewById(R.id.map)).getMap();
            if (mMap != null) {
                setUpMap();
            }
        }
    }
    private void setUpMap() {
        mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title(
                "Marker"));
    }
}

错误

The method findViewById(int) is undefined for the type PlaceMapsFragment
如果我

没记错的话,所有片段都没有本机findViewById()方法。这就是为什么你必须使用 onCreateView() 方法。

这意味着您应该将setUpMapIfNeeded()更改为setUpMapIfNeeded(View view) onCreateView()并将 v 传递给您修改后的方法。您还需要将mMap = ((MapView) findViewById(R.id.map)).getMap();更改为 mMap = ((MapView) view.findViewById(R.id.map)).getMap();

我不确定你可以对SupportMapFragment类进行子类化。

要获取SupportMapFragment的新实例,请调用SupportMapFragment.newInstance这将返回您的对象。

例如,如果你对它进行子类化并调用PlaceMapsFragment.newInstance(),你仍然会返回一个SupportMapFragment对象。

如果要以编程方式操作地图,我建议您执行以下操作。

this.mSupportMapFragment = SupportMapFragment.newInstance();
MapHandler mMapHandler = new mMapHandler(this.mSupportMapFragment.getMap());

希望这有帮助。

最新更新