java - Map 类的 onCreate() 和 onMapReady() 函数从未运行

标签 java android xml google-maps android-fragments

我创建了一个基本的 Android 应用程序,旨在提供一张 map ,上面有一个汉堡抽屉。每个汉堡菜单选项都将在 GoogleMap 对象上运行对象方法。

问题是,当汉堡抽屉创建并工作时, map 的 fragment 被放置在正确的位置,MainActivity 中的 onCreate 和随后的 onMapReady 函数没有运行,这意味着 GoogleMap 对象永远不会创建。我向这些函数添加了一些打印语句,以确保它们永远不会被打印。

我有两个类,HamburgerDrawer.java 和 MainActivity.java。

HamburgerDrawer.java:

package com.vanleusen.brighthelp;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton; 
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.google.android.gms.common.api.GoogleApiClient;

public class HamburgerDrawer extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
/**
 * ATTENTION: This was auto-generated to implement the App Indexing API.
 * See https://g.co/AppIndexing/AndroidStudio for more information.
 */
private GoogleApiClient client;

@Override
protected void onCreate(Bundle savedInstanceState) {
    //testing

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_hamburger_drawer);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);



    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    /*FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.add(R.id.frame_container, new MyFragment());
    transaction.commit();*/

    //MainActivity map = new MainActivity();

}



@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.hamburger_drawer, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_roadmap) {
        System.out.println("Roadmap");
        //mapData.mapTypeInterface(1);
    } else if (id == R.id.nav_satellite) {
        System.out.println("Satellite");
        //mapData.mapTypeInterface(2);
    } else if (id == R.id.nav_hybrid) {
        System.out.println("Hybrid");
        //mapData.mapTypeInterface(3);
    } else if (id == R.id.nav_terrain) {
        System.out.println("Terrain");
        //mapData.mapTypeInterface(4);
    } else if (id == R.id.nav_problems) {
        System.out.println("Report Problems");
    } else if (id == R.id.nav_contact) {
        System.out.println("Contact Us");
    } else if (id == R.id.nav_about) {
        System.out.println("About");
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

}

MainActivity.java:

package com.vanleusen.brighthelp;

/**
 * Created by Oscar on 22/10/2016.
 */
import android.app.Activity;
import android.os.Bundle;
import android.view.View;

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.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends Activity implements OnMapReadyCallback {
    private GoogleMap mMap;
    public static MapFragment mapFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_hamburger_drawer);

        mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        System.out.println("Ran onCreate method");
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        System.out.println("Ran onMapReady method");
        mMap = googleMap;
        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}

我有多个布局 xml 文件来实现汉堡菜单,尽管包含抽屉内容的相关文件位于此处:

content_hamburger_drawer.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_hamburger_drawer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.vanleusen.brighthelp.HamburgerDrawer"
    tools:showIn="@layout/app_bar_hamburger_drawer">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <fragment
            android:id="@+id/map"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            class="com.google.android.gms.maps.MapFragment" />

        <view
            android:id="@+id/myview"
            android:layout_width="match_parent"
            android:layout_height="fill_parent"
            class="android.view.View" />
    </FrameLayout>

</RelativeLayout>

最后,我听说这可能与我的 AndroidManifest 有关,尽管我尝试了一些更正,但似乎对我不起作用,我将其包含在下面:

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.vanleusen.brighthelp">

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality. 
    -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".HamburgerDrawer"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        launchMode ensures intents don't create multiple instances of it
        <activity
            android:name=".MainActivity"
            android:label="Map"
            android:theme="@style/AppTheme.NoActionBar"
            android:launchMode="singleTask" >
        </activity>


        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/. 
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

    </application>

</manifest>

如果有人能帮助我找出为什么我的 map 的 onCreate 和 onMapReady 函数没有被执行,我将非常感激。

最佳答案

我认为您没有从任何地方调用 MainActivity 类,这就是这个问题出现的原因。请从 onCreate 方法或任何 clicklistener 中的 HammerDrawer 类调用它。

Intent a=new Intent(getApplicationContext,MainActivity.class);
startActivity(a);

关于java - Map 类的 onCreate() 和 onMapReady() 函数从未运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40544713/

相关文章:

java - 从轴中删除负值

java - 如何在Jmeter beanshell处理器中生成timeuuid?

java - for 循环中的整数数组?

安卓指纹识别

android - NotificationManager 启动空 Activity

java - Java XSLT 转换中 newTransformer 和 newTemplates 的区别

java - Scala XML 性能与 Java XML

java - UnsatisfiedLinkError 在 Java 中使用 swig

android - GridLayout 在小显示器上折叠

android - 无法滚动 ListView