我想动态地在另一个片段中添加一个片段。 外部片段是 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();
答案 0 :(得分:2)
我记得看到片段中的片段只是动态地工作而不是放置XML。我认为Abd El-Rahman El-Tama有正确的想法使用frameLayout而不是直接指定片段
答案 1 :(得分:1)
动态更改Fragments
所需的全部内容
1) FrameLayout
中的Layout
如下:
<FrameLayout
android:id="@+id/fragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
2)将FrameLayout
初始化为activity
,如下所示: -
FrameLayout fragment = (FrameLayout) findViewById(R.id.fragment);
3)启动Fragment事务如下:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment, new MyFragment()).commit();
或者
FragmentManager fragMan = new FragmentManager();
fragMan.beginTransaction ();
fragMan.replace (R.id.fragment);
fragMan.commit ();