下面是解決方案,它只允許您在堆棧中添加一次片段,否則會彈出堆棧中相同的片段。
public static void openFragment(Activity activity, Fragment fragment) {
String fragmentTag = fragment.getClass().getName();
FragmentManager fragmentManager= ((ActionBarActivity) activity)
.getSupportFragmentManager();
boolean fragmentPopped = fragmentManager
.popBackStackImmediate(fragmentTag , 0);
if (!fragmentPopped && fragmentManager.findFragmentByTag(fragmentTag) == null) {
FragmentTransaction ftx = fragmentManager.beginTransaction();
ftx.addToBackStack(fragment.getClass().getSimpleName());
ftx.setCustomAnimations(R.anim.slide_in_right,
R.anim.slide_out_left, R.anim.slide_in_left,
R.anim.slide_out_right);
ftx.add(R.id.main_content, fragment);
ftx.commit();
}
}
slide_in_right
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="true">
<translate android:fromXDelta="100%"
android:toXDelta="0%" android:fromYDelta="0%"
android:toYDelta="0%" android:duration="200">
</translate>
</set>
slide_out_right
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<translate android:fromXDelta="0%" android:toXDelta="100%"
android:fromYDelta="0%" android:toYDelta="0%"
android:duration="200">
</translate>
</set>
slide_in_left
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="true">
<translate android:fromXDelta="-100%"
android:toXDelta="0%" android:fromYDelta="0%"
android:toYDelta="0%" android:duration="200">
</translate>
</set>
slide_out_left
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="true">
<translate android:fromXDelta="0%"
android:toXDelta="-100%" android:fromYDelta="0%"
android:toYDelta="0%" android:duration="200">
</translate>
</set>
這是你如何調用該函數:
openFragment(activity, new MyFragment());
請問,如何調用函數openFragment(???,newfragment)和動畫幻燈片的代碼xml ... – Webserveis 2016-02-19 20:42:12
檢查更新 – user3819810 2016-02-22 06:32:26