嗨 Nguyen,我创建了相同的场景,但从 activityB 回来后,fragment_2 位于顶部
这是我的代码`public class FirstActivity extends 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>