2016-07-15 11 views
4

私はGoogle Mapsに問題があります。つまり、getSupportFragmentManager()です。findFragmentByIdは常にnullを返します。これを解決する方法がありますか?ここでgetSupportFragmentManager().FindFragmentByIdは、アンドロイドのフラグメント内のGoogleマップのnullを返しますか?

コードです:

fragment_map.xml: 

<FrameLayout 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="com.myapp.something.MapFragment"> 
<fragment 
    android:id="@+id/map" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    class="com.google.android.gms.maps.SupportMapFragment" />     
</FrameLayout> 

MapsFragment.java:

public class MapFragment extends Fragment implements OnMapReadyCallback, android.location.LocationListener 

public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    SupportMapFragment mapFragment = (SupportMapFragment) this.getActivity().getSupportFragmentManager().findFragmentById(R.id.map); 
    mapFragment.getMapAsync(this); 
... 

私が活動にGoogleマップを持っており、それがコードで動作します:

SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
       .findFragmentById(R.id.map); 
     mapFragment.getMapAsync(this); 

私がしようとしていますこれをフラグメントで再利用してください。マップではなくフラグメントでマップする必要がありますが、動作しません。

私が試した: "onCreateView" 機能では、このコードを呼び出す

  • SupportMapFragment mapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
  • GoogleMap mGoogleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map)).getMap();は廃止、およびアプリケーションのクラッシュ
  • SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map); と同様のバリエーションが、すべてのケースで私が取得されますmapFragmentの場合はnull

この問題を解決するにはどうすればよいですか?

+0

あなたはフラグメントのための 'onCreateView'を使うようになりました。エラーが何であるかを知るためにここにログを投稿できますか? –

+0

もし私が 'onCreateView'を使うと、私はまだこのエラーを受け取ります。あなたは私の質問の更新でエラー報告を見ることができます –

+0

私は解決策を見つけました。ありがとう:) –

答えて

9

問題は、アクティビティのFragmentManagerを使用しようとしていて、Fragmentの子FragmentManagerを使用する必要があることです。

断片でonCreate()オーバーライドを削除し、そしてあなたがレイアウトを膨らませるとgetMapAsync()を呼び出すonCreateView()オーバーライドを追加します。

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 

    View rootView = inflater.inflate(R.layout.fragment_map, container, false); 

    SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map); 

    mapFragment.getMapAsync(this); 

    return rootView; 
} 
+0

返信のためのTnxが、このコードはまた動作しません。 'findFragmentById'はまだnullを返します。 –

+1

私は申し訳ありませんが、それは私の間違いでしたが、ITが動作します!どうもありがとうございました! :) –

+0

完了。もう一度Tnx: –

関連する問題