我有8个片段和一个活动......基于用户选择,我用适当的片段替换内容。在这里,我将片段添加到后面的堆栈中。这工作正常。当点击后退按钮片段从后面堆栈逐个显示..但这些片段再次重新加载..如何重新创建片段而不重新创建?
我试过这样的
public <T> void attachFragmentToContentView(int fragmentId) {
Fragment fragment = null;
switch (fragmentId) {
case Constants.ID_FRAGMENT_DEVICE_THEME:
fragment = DeviceThemeFragment.createInstance();
break;
case Constants.ID_FRAGMENT_CORPORATION_INFO:
fragment = CorporationInformationFragment.createInstance();
break;
case Constants.ID_FRAGMENT_NEW_OFFERS:
fragment = new NewOffersFragment<T>();
break;
case Constants.ID_FRAGMENT_ACHIEVEMENTS:
fragment = new CompanyAchievementFragment<T>();
break;
case Constants.ID_FRAGMENT_CLIENTELE:
fragment = new ClienteleFragment<T>();
break;
case Constants.ID_FRAGMENT_ONGOING_SCHEMES:
fragment = new OnGoingSchemesFragment<T>();
break;
case Constants.ID_FRAGMENT_TRACKING:
fragment = new TrackingFragment<T>();
break;
case Constants.ID_FRAGMENT_ENQUIRY_FORM:
fragment = new EnquiryFragment<T>();
break;
case Constants.ID_FRAGMENT_NEWS_EVENTS:
fragment = new NewsEventsFragment<T>();
break;
default:
comingSoon();
break;
}
if (fragment != null) {
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.content, fragment,
String.valueOf(fragmentId));
//
fragmentManager.addOnBackStackChangedListener(this);
fragmentTransaction.addToBackStack(String.valueOf(fragmentId));
fragmentTransaction.commit();
}
}
我从后台弹出时遇到问题。如果有人解决我的问题我会很感激
谢谢, Chaitanya.K
答案 0 :(得分:0)
试试这个..
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomePage();
break;
case 1:
fragment = new SecondPage();
break;
case 2:
fragment = new ThirdPage();
break;
case 3:
fragment = new SettingsPage();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction().replace(R.id.frame_container, fragment);
transaction.commit();
你应该在所有片段中都有一个构造函数。 至少这样。
public HomePage(){}
答案 1 :(得分:0)
我认为你可能不得不使用attach / detach,但首先,在创建新实例之前尝试搜索片段的现有实例:
Fragment fragment = fragmentManager.findFragmentByTag(String.valueOf(fragmentId));
if (fragment != null) {
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.attach(R.id.content, fragment);
fragmentManager.addOnBackStackChangedListener(this);
fragmentTransaction.addToBackStack(String.valueOf(fragmentId));
fragmentTransaction.commit();
}
else {
// contents of your switch statement setting fragment
if (fragment != null) {
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.content, fragment,
String.valueOf(fragmentId));
fragmentManager.addOnBackStackChangedListener(this);
fragmentTransaction.addToBackStack(String.valueOf(fragmentId));
fragmentTransaction.commit();
}
}
答案 2 :(得分:0)
如果我明白你的观点。这会对你有帮助..
@Override
public void onBackPressed(){
if (getSupportFragmentManager().getBackStackEntryCount() == 1){
finish();
}
else {
super.onBackPressed();
}
}
试试这个。