- 在xml文件中添加
<fragment android:id="@+id/fragment_one" android:name="com.xhb.fragment.TestFragment" android:layout_width="match_parent" android:layout_height="wrap_content"/>
- 在java代码中添加
FragmentManager manager=getFragmentManager(); FragmentTransaction transaction=manager.beginTransaction(); TestFragment testFragment=new TestFragment(); transaction.add(R.id.add_fragment,testFragment); TextView tv=(TextView)findViewById(R.id.item_text); tv.setText("to be or not to be"); transaction.remove(testFragment).commit(); Fragment fragment=manager.findFragmentById(R.id.fragment_one); if(fragment instanceof TestFragment){ Toast.makeText(this, "true", Toast.LENGTH_SHORT).show(); }else { Toast.makeText(this, "false", Toast.LENGTH_SHORT).show(); }