java 在谷歌地图 V2 ... fragment.getMap() 返回 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14909917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
in google maps V2 ... fragment.getMap() returns null
提问by proG
I can't get the map ! all I can get is null.
我拿不到地图!我能得到的只是空。
here is the code.
这是代码。
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SupportMapFragment fragment = new SupportMapFragment();
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, fragment).commit();
GoogleMap map;
map = fragment.getMap();
//here i cant access this snippet because map = null
if(map!=null){
UiSettings mm = map.getUiSettings();
map.setMyLocationEnabled(true);
} }
}
The manifest:
清单:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.anywhere_reminder"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<permission
android:name="com.example.anywhere_reminder.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.anywhere_reminder.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity android:name="com.google.android.gms.BuildConfig" />
<activity
android:name="com.example.anywhere_reminder.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value=" my key "/>
</application>
</manifest>
here is the xml:
这是xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
</RelativeLayout>
I tried to solve it like this solution Google Maps Android API v2 throws GooglePlayServicesNotAvailableException, out of date, SupportMapFragment.getMap() returns null.. but still did not work
我试图解决它像这个解决方案Google Maps Android API v2 throws GooglePlayServicesNotAvailableException, out of date, SupportMapFragment.getMap() 返回 null.. 但仍然没有工作
UPDATE:
更新:
I got my map working now .. here is the edited working version
我的地图现在可以工作了..这是编辑后的工作版本
public class MainActivity extends FragmentActivity {
private GoogleMap myMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android.support.v4.app.FragmentManager myFragmentManager = getSupportFragmentManager();
SupportMapFragment mySupportMapFragment
= (SupportMapFragment)myFragmentManager.findFragmentById(R.id.map);
myMap = mySupportMapFragment.getMap();
if(myMap!=null)
myMap.setMyLocationEnabled(true);
}
回答by CommonsWare
You are creating a dynamic fragment, via a FragmentTransaction
. When you call commit()
, the fragment has notyet been added to the screen, because the FragmentTransaction
has only been scheduled to occur -- it has not occurred yet. Hence, the SupportMapFragment
has not been called with onCreateView()
yet, so there is no GoogleMap
.
您正在创建一个动态片段,通过FragmentTransaction
. 当您调用 时commit()
,片段还没有添加到屏幕上,因为FragmentTransaction
它只被安排发生——它还没有发生。因此,SupportMapFragment
还没有被调用onCreateView()
,所以没有GoogleMap
。
Either switch to static fragments (<fragment>
tag in a layout), or delay your use of the GoogleMap
until after the transaction has been processed.
要么切换到静态片段(<fragment>
布局中的标签),要么延迟使用,GoogleMap
直到事务处理完毕。
回答by darias
executePendingTransactions() in FragmentManager class was designed to fix this delay. From documantstion : After a FragmentTransaction is committed with FragmentTransaction.commit(), it is scheduled to be executed asynchronously on the process's main thread. If you want to immediately executing any such pending operations, you can call this function (only from the main thread) to do so. Note that all callbacks and other related behavior will be done from within this call, so be careful about where this is called from.
FragmentManager 类中的 executePendingTransactions() 旨在解决此延迟。来自文档:在使用 FragmentTransaction.commit() 提交 FragmentTransaction 后,它被安排在进程的主线程上异步执行。如果您想立即执行任何此类挂起操作,您可以调用此函数(仅从主线程)来执行此操作。请注意,所有回调和其他相关行为都将在此调用中完成,因此请注意从何处调用它。
回答by Davide
I have extended the MapFragment class and added a listener. The doc about getMap() say:
我扩展了 MapFragment 类并添加了一个侦听器。关于 getMap() 的文档说:
... Null if the view of the fragment is not yet ready. This can happen if the fragment lifecyle have not gone through onCreateView(LayoutInflater, ViewGroup, Bundle) yet....
... 如果片段的视图尚未准备好,则为空。如果片段生命周期还没有通过 onCreateView(LayoutInflater, ViewGroup, Bundle) ,就会发生这种情况......
Then I call the listener after onCreateView. I add the class
然后我在 onCreateView 之后调用监听器。我添加类
public class MySupportMapFragment extends SupportMapFragment{
private MySupportMapFragmentListener listener;
public interface MySupportMapFragmentListener{
public void onMapCreated(GoogleMap googleMap);
}
// value taken from source code
private static final String MAP_OPTIONS = "MapOptions";
public static MySupportMapFragment newInstance() {
MySupportMapFragment f = new MySupportMapFragment();
return f;
}
public static MySupportMapFragment newInstance(GoogleMapOptions options) {
MySupportMapFragment f = new MySupportMapFragment();
Bundle args = new Bundle();
args.putParcelable(MAP_OPTIONS, options);
f.setArguments(args);
return f;
}
// other newInstance methods ...
/* (non-Javadoc)
* @see android.support.v4.app.Fragment#onViewCreated(android.view.View, android.os.Bundle)
*/
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
// here, as doc say, the map can be initialized, or the service is not available
if(listener!=null){
listener.onMapCreated(getMap());
}
}
/**
* @return the listener
*/
public MySupportMapFragmentListener getListener() {
return listener;
}
/**
* @param listener the listener to set
*/
public void setListener(MySupportMapFragmentListener listener) {
this.listener = listener;
}
}
}
After in the calling activity or fragment ...
在调用活动或片段之后...
mapFragment = MySupportMapFragment.newInstance();
mapFragment.setListener(new MySupportMapFragmentListener() {
@Override
public void onMapCreated(GoogleMap googleMap) {
// TODO Auto-generated method stub
if(googleMap!=null){
// service is unaviable
}
}
回答by Lei Zhang
Move the code snippet:
移动代码片段:
GoogleMap map; map = fragment.getMap();
谷歌地图;map = fragment.getMap();
//here map is not null
//这里地图不为空
if(map!=null){
如果(地图!=空){
UiSettings mm = map.getUiSettings();
map.setMyLocationEnabled(true);
}
}
to onResume() method, this will solve your issue.
onResume() 方法,这将解决您的问题。
回答by Lei Zhang
Another way to solve it. Implemet an interface in the MapFragment to communicate to the activity when it is ready for GoogleMap creation.
解决它的另一种方法。在 MapFragment 中实现一个接口,以便在准备好创建 GoogleMap 时与 Activity 进行通信。
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
listener.onGoogleMapCreattion();
}
Then you just need to implement the listener in the activtiy:
然后你只需要在活动中实现监听器:
@Override
public void onGoogleMapCreation() {
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
mMap = mMapFragment.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
// The Map is verified. It is now safe to manipulate the map.
setUpMap();
}
}
}