0

我正在尝试基于 hello map tutorial 构建一个简单的 Maps 应用程序,但MapView获得的findViewById返回 null。但是,地图在模拟器中正确显示。所以该应用程序有效,但我无法在代码中检索地图视图。我错过了什么?

代码:

public class HelloMapActivity extends MapActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MapView mapView = (MapView) findViewById(R.id.mapview);
        if (mapView == null) {
            Log.d("onCreate", "map is null"); //log shows that mapView is null
        }
        setContentView(R.layout.main);
    }

    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}

布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainlayout"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <com.google.android.maps.MapView
        android:id="@+id/mapview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:clickable="true"
        android:apiKey="the key"
    />

</RelativeLayout>
4

2 回答 2

5

setContentView(R.layout.main)必须在您的MapView.

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        MapView mapView = (MapView) findViewById(R.id.mapview);
        if (mapView == null) {
            Log.d("onCreate", "map is null"); //log shows that mapView is null
        }
    }


我建议您setContentView在致电后立即 添加super.onCreate(savedInstanceState)

于 2012-06-21T17:54:39.067 回答
4

setContentView(R.layout.main);应该来before MapView mapView = (MapView) findViewById(R.id.mapview);

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

         setContentView(R.layout.main); //<----------------------------------------

        MapView mapView = (MapView) findViewById(R.id.mapview);
        if (mapView == null) {
            Log.d("onCreate", "map is null"); //log shows that mapView is null
        }

    }
于 2012-06-21T17:54:17.360 回答