[英]Map inside fragment inside programmatically created view
我正在開發一個Android應用程序,其中一個活動包含3個步驟的步進器 。 我已經為每個步驟創建了一個布局,並以編程方式將其插入到活動的滾動視圖中。 一步布局如下所示:
這里的藍色矩形是在每個步驟中都不同的內容。 第一步應包含帶有兩個按鈕的地圖。 我認為,在活動之外創建片段以與地圖一起使用會更容易,而當用戶完成對地圖的處理時,僅向活動發送數據即可。
我使用以下代碼將每個步驟插入到活動中:
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" ... />"
和以下代碼,我設法成功地插入了帶有活動地圖的<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
‘藍’容器的步驟,應用程序崩潰與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;
}
如何在程序創建的視圖之一中添加片段?
剛剛解決了這個問題:
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();
而且效果很好(有一些小的布局錯誤)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.