在编程创建的视图内部映射片段

时间:2016-08-05 00:25:30

标签: android google-maps android-fragments

我正在开发一款Android应用,其中一项活动包含stepper,包含3个步骤。我已经为每个步骤创建了一个布局,并以编程方式将其插入到我的活动的scrollview中。一步布局如下所示:

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参数更改为&#34;蓝色&#34;的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;
}

问:

如何在一个以编程方式创建的视图中添加片段?

1 个答案:

答案 0 :(得分:1)

刚刚解决了问题:

UILabel

它工作正常(有较小的布局错误)。

Working map in the step

相关问题