我最近將我的應用程序從原生片段切換到了v4支持片段庫,但是現在,當我將片段從後退堆棧中彈出時,onCreateView()不會在前一個片段上調用。我需要能夠在更換碎片時更改標題中的按鈕。我試着同時使用onHiddenChanged()和setUserVisibleHint(),但當片段回到視圖中時似乎都沒有被調用。Android支持片段彈出backstack調用什麼方法?
讀另一個線程,我看到人們說要使用onBackStateChanged監聽器,但我遇到了一些問題。當我的應用程序啓動時,它會用文章列表視圖(部分)替換一個片段容器。當用戶選擇文章時,它會用文章片段替換片段片段。記錄返回棧的計數現在爲1.當用戶點擊返回按鈕時,剖面視圖再次顯示。我希望能夠調用的onResume我的部分片段,但計數爲0,並說:
09-28 00:45:17.443 21592-21592/com.reportermag.reporter E /堆棧中 大小:0顯示java.lang.NullPointerException:嘗試調用虛擬方法無效android.support.v4.app.Fragment.onResume()'上一個空對象引用
如何獲取文章列表片段的引用,因此我可以調用onResume()?
代碼我已經試過:
public void onBackStackChanged() {
android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
if (manager != null)
{
int backStackEntryCount = manager.getBackStackEntryCount();
Log.e("Backstack size", Integer.toString(backStackEntryCount));
android.support.v4.app.Fragment fragment = manager.getFragments().get(backStackEntryCount > 0 ? backStackEntryCount-1:backStackEntryCount);
fragment.onResume();
}
}
public void setUserVisibleHint(boolean visible)
{
super.setUserVisibleHint(visible);
if (visible && isResumed())
{
// Set the titlebar
Titlebar.setColor(getResources().getColor(R.color.graydark));
Titlebar.setVisible(Titlebar.VIEWS.MENU, Titlebar.VIEWS.LOGO, Titlebar.VIEWS.SEARCH);
// Clear Search
SearchFragment.clearSearch();
}
}
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if(hidden == false) {
// Set the titlebar
Titlebar.setColor(getResources().getColor(R.color.graydark));
Titlebar.setVisible(Titlebar.VIEWS.MENU, Titlebar.VIEWS.LOGO, Titlebar.VIEWS.SEARCH);
// Clear Search
SearchFragment.clearSearch();
}
}
更新:
這裏是我的片段裝載機:
public void loadSectionFragment(Integer sectionID) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Set the arguments
Bundle bundle = new Bundle();
bundle.putInt("section", sectionID);
// Add the section fragment
Fragment sectionFrag = sections.get(sectionID);
if (sectionFrag == null) {
sectionFrag = new SectionFragment();
sectionFrag.setArguments(bundle);
sections.put(sectionID, sectionFrag);
}
transaction.setCustomAnimations(R.animator.enter_anim, R.animator.exit_anim);
transaction.replace(R.id.fragment_container, sectionFrag);
transaction.addToBackStack(null);
// Commit the new fragment
transaction.commit();
}
public void loadArticleFragment() {
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
// Set the arguments
Bundle bundle = new Bundle();
bundle.putInt("id", id);
bundle.putInt("color", color);
// Add the article fragment
Fragment articleFrag = new ArticleFragment();
articleFrag.setArguments(bundle);
transaction.replace(R.id.fragment_container, articleFrag);
transaction.addToBackStack(null);
// Commit the new fragment
transaction.commit();
}
你還添加片段返回堆棧? – Olu
抱歉應該發佈該代碼。我將它添加到了後臺。在我的主要onCreate它調用loadSectionFragment()。儘管如此,後臺數仍然是0。 –
而不是替換(containerId,片段)你可以檢查與添加(containerId,片段)..我認爲這是問題.. – user2906641