2016-08-05 23 views
0

我正在使用一個活動,其中包含stepper三個步驟的Android應用程序。我爲每個步驟創建了一個佈局,並以編程方式將其插入到我的活動的滾動視圖中。一步佈局是這樣的:以編程方式創建視圖中的內部片段映射

Step layout

這裏的藍色矩形是,這將是在每個步驟的不同內容。第一步應該包含帶有幾個按鈕的地圖。我認爲,使用片段來處理活動外的地圖並在用戶完成地圖工作時將數據發送到活動會更容易。

我插入每個步驟與該代碼的活性:

View step1, step2, step3; // they are global 

//Inside onCreate: 
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
FrameLayout mainView = (FrameLayout) inflater.inflate(R.layout.activity_main, null); 
LinearLayout parent = (LinearLayout) mainView.findViewById(R.id.stepper_container); 

step1 = inflater.inflate(R.layout.layout_step, null); 
parent.addView(step1); 
step2 = inflater.inflate(R.layout.layout_step, null); 
parent.addView(step2); 
step3 = inflater.inflate(R.layout.layout_step, null); 
parent.addView(step3); 
setContentView(mainView); 

我設法通過創建在其中的<FragmentLayout android:id="@+id/fragment_container" ... />"成功插入與地圖到活動片段和下面的代碼:

FragmentManager fragmentManager = getSupportFragmentManager(); 
FragmentTransaction transaction = fragmentManager.beginTransaction(); 
OfficeMapFragment map = OfficeMapFragment.newInstance(); 
transaction.add(R.id.fragment_container, map); 
transaction.commit(); 

但我不能用新的程序添加視圖來做,因爲它們的元素'id'是相同的,並且當我將交易中的id參數更改爲「藍色」容器的id i第n步,應用程序崩潰與NullPointerException。

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference 

OfficeMapFragment onCreateView方法:

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    // Inflate the layout for this fragment 
    View v = inflater.inflate(R.layout.fragment_map, container, false); 
    SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager() 
      .findFragmentById(R.id.map); 
    mapFragment.getMapAsync(this); // It crashes here 
    return v; 
} 

問:

如何添加里面的編程方式創建一個視圖的片段?

回答

1

就解決了這個問題:

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    FrameLayout mainView = (FrameLayout) inflater.inflate(R.layout.activity_main, null); 
    LinearLayout parent = (LinearLayout) mainView.findViewById(R.id.stepper_container); 
    step1 = inflater.inflate(R.layout.layout_step, null); 
    parent.addView(step1); 
    // Other steps 
    setContentView(mainView); 
    FrameLayout container = (FrameLayout) step1.findViewById(R.id.step_content_container); 

    fragmentManager = getSupportFragmentManager(); 
    FragmentTransaction transaction = fragmentManager.beginTransaction(); 
    OfficeMapFragment map = OfficeMapFragment.newInstance(); 
    transaction.add(container.getId(), map); 
    transaction.commit(); 

,它工作正常(含有少量佈局錯誤)。

Working map in the step