【发布时间】:2014-04-24 15:29:42
【问题描述】:
我使用 OSM 创建了一个简单的地图应用程序。一切正常,但是当我尝试使用 findViewById 来表示布局中的地图时出现问题。
我收到了这个错误:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.openstreetmaptutorial/com.example.openstreetmaptutorial.MainActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
活动代码:
public class MainActivity extends Activity {
double myCurrentLatitude;
double myCurrentLongitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get current location
GPSTracker tracker = new GPSTracker(this);
if (tracker.canGetLocation() == false) {
tracker.showSettingsAlert();
} else {
myCurrentLatitude = tracker.getLatitude();
myCurrentLongitude = tracker.getLongitude();
}
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setClickable(true);
mapView.setBuiltInZoomControls(true);
mapView.setTileSource(TileSourceFactory.MAPQUESTOSM);
mapView.getController().setZoom(15);
mapView.getController().setCenter(new GeoPoint(myCurrentLatitude, myCurrentLongitude));
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.pin_for_map);
MapItemizedOverlay itemizedoverlay = new MapItemizedOverlay(drawable,this);
itemizedoverlay.setEnabled(true);
//setting pin to my current position on the map
GeoPoint homePoint = new GeoPoint(myCurrentLatitude,myCurrentLongitude);
OverlayItem overlayitem = new OverlayItem("Home Sweet Home", "name", homePoint);
mapView.getController().setZoom(15);
mapView.getController().setCenter(homePoint);
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
setContentView(mapView);
}
}
布局文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<org.osmdroid.views.MapView
android:id="@+id/mapview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:enabled="true"
android:clickable="true"
/>
</RelativeLayout>
实际上导致错误的行是:
MapView mapView = (MapView) findViewById(R.id.mapview);
如果我将行更改为:
MapView mapView = new MapView(this, 256);
那么就没有错误了。但我需要实现前一个,因为我想通过 xml 向布局添加更多控件。我应该怎么做才能克服这个问题?我可以在没有指定错误的情况下使用 findViewById 吗?
【问题讨论】:
标签: java android android-mapview findviewbyid