Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/188.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 导航抽屉未显示但仍在打开_Java_Android_Navigation Drawer_Nutiteq - Fatal编程技术网

Java 导航抽屉未显示但仍在打开

Java 导航抽屉未显示但仍在打开,java,android,navigation-drawer,nutiteq,Java,Android,Navigation Drawer,Nutiteq,我使用的是Nutiteq SDK,它拥有一个MapView,我还试图使用一个导航抽屉。我遇到的问题是,每当我从左侧滑动或单击图标打开抽屉时,都不会打开任何东西,但在我向后滑动抽屉或再次单击图标之前,我无法移动地图。这让我相信抽屉是打开的,但没有展示。以下是我的MainActivity.java和activity_main.xml: MainActivity.java public class MainActivity extends Activity { private MapView ma

我使用的是Nutiteq SDK,它拥有一个MapView,我还试图使用一个导航抽屉。我遇到的问题是,每当我从左侧滑动或单击图标打开抽屉时,都不会打开任何东西,但在我向后滑动抽屉或再次单击图标之前,我无法移动地图。这让我相信抽屉是打开的,但没有展示。以下是我的MainActivity.java和activity_main.xml:

MainActivity.java

public class MainActivity extends Activity {

 private MapView mapView;
 private LocationListener locationListener;
 private GeometryLayer locationLayer; 
 private Timer locationTimer;

 private String[] drawerListViewItems;
 private ListView drawerListView;
 private DrawerLayout drawerLayout;
 private ActionBarDrawerToggle actionBarDrawerToggle;

 @Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);

     setMap();

     // get list items from strings.xml
     drawerListViewItems = getResources().getStringArray(R.array.items);

     // get ListView defined in activity_main.xml
     drawerListView = (ListView) findViewById(R.id.left_drawer);

     // Set the adapter for the list view
     drawerListView.setAdapter(new ArrayAdapter<String>(this, 
                R.layout.drawer_listview_item, drawerListViewItems));

     // App Icon 
     drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

     actionBarDrawerToggle = new ActionBarDrawerToggle(
             this,                  /* host Activity */
             drawerLayout,         /* DrawerLayout object */
             R.drawable.ic_drawer,  /* nav drawer icon to replace 'Up' caret */
             R.string.drawer_open,  /* "open drawer" description */
             R.string.drawer_close  /* "close drawer" description */
             );

     // Set actionBarDrawerToggle as the DrawerListener
     drawerLayout.setDrawerListener(actionBarDrawerToggle);

     getActionBar().setDisplayHomeAsUpEnabled(true); 

     // just styling option add shadow the right edge of the drawer
     drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);


 }

 @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        actionBarDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

         // call ActionBarDrawerToggle.onOptionsItemSelected(), if it returns true
        // then it has handled the app icon touch event
        if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

 @Override
 public Object onRetainNonConfigurationInstance() {
     Log.debug("onRetainNonConfigurationInstance");
     return this.mapView.getComponents();
 }

 @Override
 protected void onStart() {
     super.onStart();

     // 4. Start the map - mandatory.
     mapView.startMapping();

     // Create layer for location circle
     locationLayer = new GeometryLayer(mapView.getLayers().getBaseProjection());
     mapView.getComponents().layers.addLayer(locationLayer);

     // add GPS My Location functionality 
     final MyLocationCircle locationCircle = new MyLocationCircle(locationLayer);
     initGps(locationCircle);

     // Run animation
     locationTimer = new Timer();
     locationTimer.scheduleAtFixedRate(new TimerTask() {
         @Override
         public void run() {
             locationCircle.update(mapView.getZoom());
         }
     }, 0, 50);
 }

 @Override
 protected void onStop() {
     // Stop animation
     locationTimer.cancel();

     // Remove created layer
     mapView.getComponents().layers.removeLayer(locationLayer);

     // remove GPS support, otherwise we will leak memory
     deinitGps();

     // Note: it is recommended to move startMapping() call to onStart method and implement onStop method (call MapView.stopMapping() from onStop). 
     mapView.stopMapping();

     super.onStop();
 }

 @Override
 protected void onPostCreate(Bundle savedInstanceState) {
      super.onPostCreate(savedInstanceState);
      // Sync the toggle state after onRestoreInstanceState has occurred.
      actionBarDrawerToggle.syncState();
 }

 @Override
 protected void onDestroy() {
     super.onDestroy();
 }

 protected void initGps(final MyLocationCircle locationCircle) {
     final Projection proj = mapView.getLayers().getBaseLayer().getProjection();

     locationListener = new LocationListener() {
         @Override
         public void onLocationChanged(Location location) {
              locationCircle.setLocation(proj, location);
              locationCircle.setVisible(true);

              // recenter automatically to GPS point
              // TODO in real app it can be annoying this way, add extra control that it is done only once
              mapView.setFocusPoint(mapView.getLayers().getBaseProjection().fromWgs84(location.getLongitude(), location.getLatitude()));
         }

         @Override
         public void onStatusChanged(String provider, int status, Bundle extras) {
             Log.debug("GPS onStatusChanged "+provider+" to "+status);
         }

         @Override
         public void onProviderEnabled(String provider) {
             Log.debug("GPS onProviderEnabled");
         }

         @Override
         public void onProviderDisabled(String provider) {
             Log.debug("GPS onProviderDisabled");
         }
     };

     LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
     List<String> providers = locationManager.getProviders(true);
     for(String provider : providers){
         locationManager.requestLocationUpdates(provider, 10000, 100, locationListener);
     }

 }

 protected void deinitGps() {
     // remove listeners from location manager - otherwise we will leak memory
     LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
     locationManager.removeUpdates(locationListener);    
 }

 // adjust zooming to DPI, so texts on rasters will be not too small
 // useful for non-retina rasters, they would look like "digitally zoomed"
 private void adjustMapDpi() {
     DisplayMetrics metrics = new DisplayMetrics();
     getWindowManager().getDefaultDisplay().getMetrics(metrics);
     float dpi = metrics.densityDpi;
     // following is equal to  -log2(dpi / DEFAULT_DPI)
     float adjustment = (float) - (Math.log(dpi / DisplayMetrics.DENSITY_HIGH) / Math.log(2));
     Log.debug("adjust DPI = "+dpi+" as zoom adjustment = "+adjustment);
     mapView.getOptions().setTileZoomLevelBias(adjustment / 2.0f);
 }

 private void addCartoDbLayer() {

        //  5.1 Define styles for all possible geometry types
        int color = Color.BLUE;
        int minZoom = 5;

        final Bitmap pointMarker = UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.point);
        final StyleSet<PointStyle> pointStyleSet = new StyleSet<PointStyle>();
        PointStyle pointStyle = PointStyle.builder().setBitmap(pointMarker).setSize(0.05f).setColor(color).setPickingSize(0.2f).build();
        pointStyleSet.setZoomStyle(minZoom, pointStyle);

        final StyleSet<LineStyle> lineStyleSet = new StyleSet<LineStyle>();
        LineStyle lineStyle = LineStyle.builder().setWidth(0.04f).setColor(Color.WHITE).build();
        lineStyleSet.setZoomStyle(minZoom, lineStyle);

        final StyleSet<PolygonStyle> polygonStyleSet = new StyleSet<PolygonStyle>(null);
        PolygonStyle polygonStyle = PolygonStyle.builder().setColor(0xFFFF6600 & 0x80FFFFFF).setLineStyle(lineStyle).build();
        polygonStyleSet.setZoomStyle(minZoom, polygonStyle);

        String account = "bitciv";
        String table = "units"; // kihelkonnad_1897, maakond_20120701
        String columns = "cartodb_id,name,iso2,pop2005,area,the_geom_webmercator"; // NB! always include cartodb_id and the_geom_webmercator
        //String columns = "cartodb_id,job,the_geom_webmercator";
        int limit = 5000; // max number of objects
        String sql = "SELECT "+columns+" FROM "+table+" WHERE the_geom_webmercator && ST_SetSRID('BOX3D(!bbox!)'::box3d, 3857) LIMIT "+limit;

        //      String sql2 = "SELECT name, type, oneway, osm_id, the_geom_webmercator FROM osm_roads WHERE type in ('trunk','primary') AND the_geom_webmercator && ST_SetSRID('BOX3D(!bbox!)'::box3d, 3857) LIMIT 500";
        //      String sql2 = "SELECT name, type, oneway, osm_id, the_geom_webmercator FROM osm_roads WHERE the_geom_webmercator && ST_SetSRID('BOX3D(!bbox!)'::box3d, 3857) LIMIT 500";

        CartoDbDataSource cartoDataSource = new CartoDbDataSource(mapView.getLayers().getBaseLayer().getProjection(), account, sql) {

            @Override
            protected Label createLabel(Map<String, String> userData) {
                StringBuffer labelTxt = new StringBuffer();
                for (Map.Entry<String, String> entry : userData.entrySet()){
                    labelTxt.append(entry.getKey() + ": " + entry.getValue() + "\n");
                }
                return new DefaultLabel("Data:", labelTxt.toString());
            }

            @Override
            protected StyleSet<PointStyle> createPointStyleSet(Map<String, String> userData, int zoom) {
                return pointStyleSet;
            }

            @Override
            protected StyleSet<LineStyle> createLineStyleSet(Map<String, String> userData, int zoom) {
                return lineStyleSet;
            }

            @Override
            protected StyleSet<PolygonStyle> createPolygonStyleSet(Map<String, String> userData, int zoom) {
                return polygonStyleSet;
            }

        };

        GeometryLayer cartoLayerTrunk = new GeometryLayer(cartoDataSource);
        mapView.getLayers().addLayer(cartoLayerTrunk);

    }

 private void setMap(){

    // enable logging for troubleshooting - optional
     Log.enableAll();
     Log.setTag("hellomap");

     // 1. Get the MapView from the Layout xml - mandatory
     mapView = (MapView) findViewById(R.id.mapView);

     // Optional, but very useful: restore map state during device rotation,
     // it is saved in onRetainNonConfigurationInstance() below
     Components retainObject = (Components) getLastNonConfigurationInstance();
     if (retainObject != null) {
         // just restore configuration and update listener, skip other initializations
         mapView.setComponents(retainObject);
         return;
     } else {
         // 2. create and set MapView components - mandatory
         mapView.setComponents(new Components());
     }

     // 3. Define map layer for basemap - mandatory.
     // Here we use MapQuest open tiles.
     // We use online data source for the tiles and the URL is given as template. Almost all online tiled maps use EPSG3857 projection.
     RasterDataSource dataSource = new HTTPRasterDataSource(new EPSG3857(), 0, 18, "http://otile1.mqcdn.com/tiles/1.0.0/osm/{zoom}/{x}/{y}.png");

     RasterLayer mapLayer = new RasterLayer(dataSource, 0);

     mapView.getLayers().setBaseLayer(mapLayer);

     adjustMapDpi();

     // Show performance indicator
     //mapView.getOptions().setFPSIndicator(true);

     // Increase raster tile download speed by doing 4 downloads in parallel
     //mapView.getOptions().setRasterTaskPoolSize(4);

     // set initial map view camera - optional. "World view" is default
     // Location: San Francisco 
     // NB! it must be in base layer projection (EPSG3857), so we convert it from lat and long
     mapView.setFocusPoint(mapView.getLayers().getBaseLayer().getProjection().fromWgs84(-122.41666666667f, 37.76666666666f));
     // rotation - 0 = north-up
     mapView.setMapRotation(0f);
     // zoom - 0 = world, like on most web maps
     mapView.setZoom(16.0f);
     // tilt means perspective view. Default is 90 degrees for "normal" 2D map view, minimum allowed is 30 degrees.
     mapView.setTilt(65.0f);

     // Activate some mapview options to make it smoother - optional
     mapView.getOptions().setPreloading(true);
     mapView.getOptions().setSeamlessHorizontalPan(true);
     mapView.getOptions().setTileFading(true);
     mapView.getOptions().setKineticPanning(true);
     mapView.getOptions().setDoubleClickZoomIn(true);
     mapView.getOptions().setDualClickZoomOut(true);

     // set sky bitmap - optional, default - white
     mapView.getOptions().setSkyDrawMode(Options.DRAW_BITMAP);
     mapView.getOptions().setSkyOffset(4.86f);
     mapView.getOptions().setSkyBitmap(
             UnscaledBitmapLoader.decodeResource(getResources(),
                     R.drawable.sky_small));

     // Map background, visible if no map tiles loaded - optional, default - white
     mapView.getOptions().setBackgroundPlaneDrawMode(Options.DRAW_BITMAP);
     mapView.getOptions().setBackgroundPlaneBitmap(
             UnscaledBitmapLoader.decodeResource(getResources(),
                     R.drawable.background_plane));
     mapView.getOptions().setClearColor(Color.WHITE);

     // configure texture caching - optional, suggested 
     mapView.getOptions().setTextureMemoryCacheSize(40 * 1024 * 1024);
     mapView.getOptions().setCompressedMemoryCacheSize(8 * 1024 * 1024);

     // define online map persistent caching - optional, suggested. Default - no caching
     mapView.getOptions().setPersistentCachePath(this.getDatabasePath("mapcache").getPath());
     // set persistent raster cache limit to 100MB
     mapView.getOptions().setPersistentCacheSize(100 * 1024 * 1024);

    /* // 5. Add simple marker to map. 
     // define marker style (image, size, color)
     Bitmap pointMarker = UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.olmarker);
     MarkerStyle markerStyle = MarkerStyle.builder().setBitmap(pointMarker).setSize(0.5f).setColor(Color.WHITE).build();

     // define label what is shown when you click on marker
     Label markerLabel = new DefaultLabel("San Francisco", "Here is a marker");

     // define location of the marker, it must be converted to base map coordinate system
     MapPos markerLocation = mapLayer.getProjection().fromWgs84(-122.416667f, 37.766667f);

     // create layer and add object to the layer, finally add layer to the map. 
     // All overlay layers must be same projection as base layer, so we reuse it
     MarkerLayer markerLayer = new MarkerLayer(mapLayer.getProjection());
     markerLayer.add(new Marker(markerLocation, markerLabel, markerStyle, null));
     mapView.getLayers().addLayer(markerLayer); */

     // add event listener
     MyMapEventListener mapListener = new MyMapEventListener(this, mapView);
     mapView.getOptions().setMapListener(mapListener);

     // 5. Add CartoDB vector layer to map
     addCartoDbLayer();

 }
公共类MainActivity扩展活动{
私有地图视图;
私有位置侦听器位置侦听器;
专用几何图层定位层;
私人定时器定位定时器;
私有字符串[]抽屉列表视图项;
私有列表视图抽屉列表视图;
私人抽屉布局;
私人动作bardrawertoggle动作bardrawertoggle;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setMap();
//从strings.xml获取列表项
DroperListViewItems=getResources().getStringArray(R.array.items);
//获取在activity_main.xml中定义的ListView
抽屉列表视图=(列表视图)findViewById(R.id.left\u抽屉);
//设置列表视图的适配器
DroperListView.setAdapter(新阵列适配器)(此,
R.layout.drawer_listview_item,drawerlistview items));
//应用程序图标
抽屉布局=(抽屉布局)findViewById(R.id.抽屉布局);
actionBarDrawerToggle=新actionBarDrawerToggle(
此,/*主机活动*/
抽屉布局,/*抽屉布局对象*/
R.drawable.ic_抽屉,/*导航抽屉图标替换“Up”插入符号*/
R.string.drawer\u open,/*“open drawer”说明*/
R.string.drawer\u close/*“close drawer”说明*/
);
//将actionBarDrawerToggle设置为抽屉侦听器
抽屉布局。setDrawerListener(actionBarDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
//只是样式选项添加阴影抽屉的右边缘
drawerLayout.setDrawerShadow(R.drawable.drawer\u shadow,GravityCompat.START);
}
@凌驾
公共无效OnConfiguration已更改(配置newConfig){
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
//如果返回true,则调用ActionBarDrawerToggle.onOptions ItemSelected()
//然后它处理了应用程序图标触摸事件
如果(actionBarDrawerToggle.onOptionsItemSelected(项目)){
返回true;
}
返回super.onOptionsItemSelected(项目);
}
@凌驾
公共对象OnRetainOnConfiguration实例(){
调试(“onRetainonConfiguration实例”);
返回此.mapView.getComponents();
}
@凌驾
受保护的void onStart(){
super.onStart();
//4.启动地图-必填项。
mapView.startMapping();
//为定位圈创建图层
locationLayer=new GeometryLayer(mapView.getLayers().getBaseProjection());
mapView.getComponents().layers.addLayer(locationLayer);
//添加GPS我的位置功能
最终MyLocationCircle locationCircle=新MyLocationCircle(locationLayer);
初始GPS(定位圈);
//运行动画
locationTimer=新计时器();
locationTimer.scheduleAtFixedRate(新TimerTask(){
@凌驾
公开募捐{
locationCircle.update(mapView.getZoom());
}
}, 0, 50);
}
@凌驾
受保护的void onStop(){
//停止动画
locationTimer.cancel();
//删除创建的图层
mapView.getComponents().layers.removeLayer(locationLayer);
//移除GPS支持,否则我们将泄漏内存
脱硝;
//注意:建议将startMapping()调用移动到onStart方法并实现onStop方法(从onStop调用MapView.stopMapping()。
stopMapping();
super.onStop();
}
@凌驾
后期创建时受保护的空(捆绑包savedInstanceState){
super.onPostCreate(savedInstanceState);
//在onRestoreInstanceState发生后同步切换状态。
actionBarDrawerToggle.syncState();
}
@凌驾
受保护的空onDestroy(){
super.ondestory();
}
受保护的无效初始GPS(最终MyLocationCircle位置Circle){
最终投影项目=mapView.getLayers().getBaseLayer().getProjection();
locationListener=新locationListener(){
@凌驾
已更改位置上的公共无效(位置){
locationCircle.setLocation(项目,位置);
locationCircle.setVisible(真);
//自动重新居中到GPS点
//在真实的应用程序中,这样做可能会很烦人,添加额外的控件,使其只执行一次
mapView.setFocusPoint(mapView.getLayers().getBaseProjection().fromWgs84(location.GetLength(),location.getLatitude());
}
@凌驾
public void onStatusChanged(字符串提供程序、int状态、Bundle extra){
Log.debug(“GPS onStatusChanged”+提供程序+”变为“+状态);
}
@凌驾
公共无效onProviderEnabled(字符串提供程序){
Log.debug(“GPS onProviderEnabled”);
}
@凌驾
公共无效onProviderDisabled(字符串提供程序){
Log.debug(“GPS onProviderDisabled”);
}
};
LocationManager LocationManager=(LocationManager)this.getSystemService(Context.LOCATION\u服务);
List providers=locationManager.getProviders(true);
for(字符串提供程序:提供程序){
locationManager.RequestLocationUpdate(提供程序,10000,100,locationListener);
}
}
受保护的void denitgps(){
//从位置管理器中删除侦听器-否则我们将泄漏内存
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<!-- The main content view -->

<FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.nutiteq.MapView
    android:id="@+id/mapView"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" />

</FrameLayout>

<!-- The navigation drawer -->

<ListView android:id="@+id/left_drawer"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:choiceMode="singleChoice"
    android:divider="@android:color/transparent"
    android:dividerHeight="0dp"
    android:background="#111"/>



</android.support.v4.widget.DrawerLayout>