嗨阮我創造了同樣的場景,但在上面得到fragment_2從activityB
回來後
這是我的代碼 `公共類FirstActivity擴展ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment1()).commit();
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment1 extends Fragment {
public PlaceholderFragment1() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_first, container, false);
Button button = (Button) rootView.findViewById(R.id.btn);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment2()).commit();
}
});
return rootView;
}
}
public static class PlaceholderFragment2 extends Fragment {
public PlaceholderFragment2() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_second, container, false);
Button button = (Button) rootView.findViewById(R.id.btn);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), Secondctivity.class);
startActivity(intent);
}
});
return rootView;
}
}
} `
這是我的清單文件
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".FirstActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Secondctivity"
android:label="@string/title_activity_secondctivity" >
</activity>
</application>
你在fragment_2中嘗試過'setRetainInstance(true)'嗎? –
在哪裏可以使用?我把它放在'onCreateView'中,它沒有任何作用。 –
如果您在使用片段時自定義後退導航,請在Activity中使用此行.Fragment currentfragment = getSupportFragmentManager()。findFragmentById(R.id.view); which給出當前可見片段實例... if(currentfragment instanceof yourFragment) {//您的代碼} – Vishwa