如果使用支持lib Fragment或使用本机片段(不兼容lib),则下面的代码行为不同。 使用支持lib,下面的代码破坏了BFragment。 使用原生片段,NFragment将被销毁。
有谁知道为什么会有这种差异?
public class MainActivity extends Activity {
class BFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View inflated = inflater.inflate(R.layout.dummy, container, false);
((TextView) inflated.findViewById(R.id.txt_dummy)).setText("BFragment");
return inflated;
}
}
class NFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View inflated = inflater.inflate(R.layout.dummy, container, false);
((TextView) inflated.findViewById(R.id.txt_dummy)).setText("NFragment");
return inflated;
}
}
static NFragment nfragment;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nfragment = new NFragment();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.fragment_container, new BFragment()).addToBackStack(null).commit();
fm.beginTransaction().replace(R.id.notification_container, nfragment).commit();
fm.beginTransaction().replace(R.id.fragment_container, new BFragment()).addToBackStack(null).commit();
fm.beginTransaction().replace(R.id.notification_container, nfragment).commit();
return true;
}
}
activity_main.xml是这样的:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="@+id/notification_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
/>
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="100dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
/>
</RelativeLayout>
这是dummy.xml(片段使用):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/txt_dummy"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>