2013-09-27 53 views
0

我正在實現包裹在片段中的Google Maps視圖。當我嘗試獲取mapsView的ID時,即使我的課程延伸了FragmentActivity,我也會從getSupportFragmentManager()獲得nullpointer例外。這是我的代碼:GetSupportFragmentManager()參數返回null

MainActivity:

import android.app.Activity; 
import android.os.Bundle; 
import android.support.v4.app.FragmentActivity; 
import android.widget.TabHost; 
import android.widget.TabHost.OnTabChangeListener; 

public class MainActivity extends Activity implements OnTabChangeListener { 

private TabHost mTabHost; 
private Layouts l; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Util.setMainActivty(this); 

    l = new Layouts(); 

} 

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

@Override 
public void onClick(View v) { 
     l.setMapsLayout(); 
} 
} 

我maps_layout片段

<?xml version="1.0" encoding="utf-8"?> 
<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" /> 

佈局類:

import android.support.v4.app.FragmentActivity; 
import android.support.v4.app.LoaderManager; 
import android.text.GetChars; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 

import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.MapFragment; 
import com.google.android.gms.maps.MapView; 
import com.google.android.gms.maps.SupportMapFragment; 


public class Layouts extends FragmentActivity { 

private MapView mMapView; 

public void setMapsLayout() { 

    MainActivity mainActivity = Util.getMainActivity(); 
    ViewGroup layoutContainer = (ViewGroup) mainActivity 
      .findViewById(R.id.layoutContainer); 
    layoutContainer.removeAllViews(); 


    View child1 = LayoutInflater.from(mainActivity).inflate(
      R.layout.maps_layout, null); 
    layoutContainer.addView(child1); 


    GoogleMap mMap = ((SupportMapFragment) getSupportFragmentManager() 
      .findFragmentById(R.id.map)).getMap(); 


} 


} 

當我到getSupportFragmentManager()它的值是零。這是我看到:enter image description here

有人知道問題是什麼嗎?謝謝!

回答

0

您不能僅從另一個Activity創建Activity的實例並像那樣使用它。我不確定你想要達到什麼目標,但你需要改變你的代碼才能使它工作。

0

您可以將MainActivity擴展爲FragmentActivity,因爲谷歌地圖支持FragmentActivity。 Inside MainActivity活動類,可以實現setMapsLayout()該方法。

相關問題