findFragmentById为SupportMapFragment在Android的工作室返回null [英] findFragmentById for SupportMapFragment returns null in Android Studio
问题描述
最近,我从迁移的Eclipse项目到Android工作室。一切设置和工作正常,除了我的一个片段,它使用一个SupportMapFragment。下面findFragmentById(在Eclipse构建时,它的工作),现在返回null :(
Recently I migrated a project from Eclipse to Android Studio. Everything is setup and working fine except for my one fragment which uses a SupportMapFragment. The below findFragmentById (which worked when building in Eclipse) is now returning null :(
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
SupportMapFragment m = ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.safety_map));
XML的片段...
snippet of xml...
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<fragment
android:id="@+id/safety_map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="40dp"
map:cameraTargetLat="@string/livesafe_latitude"
map:cameraTargetLng="@string/livesafe_longitude"
map:uiZoomControls="false"
class="com.google.android.gms.maps.SupportMapFragment"/>
下面是我的build.gradle我的依赖关系:
Here are my dependencies in my build.gradle:
dependencies {
//google analytics
compile 'com.google.apis:google-api-services-analytics:v3-rev103-1.19.0'
//support library for api 10
compile 'com.android.support:support-v4:21.0.0'
//google play services
compile 'com.google.android.gms:play-services:6.1.11'
compile project(':facebook')
compile files('libs/android-support-multidex.jar')
compile files('libs/aws-android-sdk-1.6.0-debug.jar')
compile files('libs/FlurryAnalytics_3.3.2.jar')
}
我并没有改变任何code在XML文件或$ P $在Eclipse pviously工作的片段类。
I haven't changed any code in the xml file or the Fragment class that previously worked in Eclipse.
推荐答案
由你改写的事实来看 Fragment.onActivityCreated()
,我认为你的包含地图片段布局是你的片段
的布局。在这种情况下, SupportMapFragment
是孩子的您的主机片段片段
。当您试图找回它,你使用的活动
FragmentManager
。您应该改用你的片段
的 FragmentManager
:
Judging by the fact that you're overriding Fragment.onActivityCreated()
, I take it that your layout containing the map fragment is the layout for your Fragment
. In that case, the SupportMapFragment
is a child fragment of your hosting Fragment
. When you attempt to retrieve it, you're using the Activity
FragmentManager
. You should instead use your Fragment
's FragmentManager
:
例如,这样的:
SupportMapFragment m = ((SupportMapFragment) getActivity()
.getSupportFragmentManager().findFragmentById(R.id.safety_map));
变成了:
SupportMapFragment m = ((SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.safety_map));
这篇关于findFragmentById为SupportMapFragment在Android的工作室返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!