我想動態地在另一個片段內添加一個片段。 外片段是DialogFragment:動態地在另一個片段內添加一個片段
public class MapFragmentDialog extends DialogFragment implements OnMapClickListener, OnMapLongClickListener,
OnMarkerDragListener {
FragmentManager fmanager;
Fragment fragment;
SupportMapFragment supportmapfragment;
public static MapFragmentDialog newInstance() {
MapFragmentDialog f = new MapFragmentDialog();
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.map_fragment, container, false);
// *********** add myMapFragment
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// add a fragment
MyMapFragment myFragment = new MyMapFragment();
fragmentTransaction.add(R.id.myfragment, myFragment);
fragmentTransaction.commit();
myMap = ((SupportMapFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.myMap)).getMap();
return v;
}
的map_fragment佈局是這樣的:
<TextView
android:id="@+id/txtHelp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:paddingBottom="6dip"
android:textAlignment="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textSize="12sp" />
<FrameLayout
android:id="@+id/myfragment"
android:layout_width="0px"
android:layout_height="wrap_content" />
我的內片段MyMapFragment:
public class MyMapFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.my_map_fragment, container, false);
return myFragmentView;
}}
的my_map_fragment佈局包含:
<fragment
android:id="@+id/myMap"
android:layout_width="match_parent"
android:layout_height="300dp"
class="com.google.android.gms.maps.SupportMapFragment" />
我得到一個異常的讓我的DialogFragment地圖片段,一個NullPointerException這行
myMap = ((SupportMapFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.myMap)).getMap();
要麼返回'getActivity()'或'getSupportFragmentManager()'或'findFragmentById(R.id.myMap)'返回null – donfuxx