簡體   English   中英

如何使用活動顯示的片段轉到上一個活動

[英]How can I go to previous activity with the fragment the activity was showing

我有兩個活動,活動A和活動B。現在活動A有3個Fragments ,其中一個啟動活動B。當我按操作欄按鈕時,它返回活動A,但顯示默認Fragment 我正在使用navUtils.navigateupFromSameTask返回上一個Activity

我如何顯示用戶使用的最新Fragment ,而不是用戶首次啟動應用程序時顯示的默認Fragment 例如,當應用啟動時,它會顯示Fragment一。 當用戶轉到Fragment 2並從中啟動活動B時,我想回到顯示片段2的上一個活動

@Override
public boolean onOptionsItemSelected(MenuItem item){
    switch(item.getItemId()){
    case android.R.id.home:
        NavUtils.navigateUpFromSameTask(this);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

在onCreate方法中

if (savedInstanceState == null) {
    fragmentManager = getFragmentManager();
    fragment = new RadioSound();
    selectItem(0);
}

然后selectItem

 private void selectItem(int position) {

    // update the main content by replacing fragments
 activeFrag = position;
 if(position == 0){
    fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
 }
 else if(position == 1){
     if(conv == null)
     conv = new Conversations();
     fragmentManager.beginTransaction().replace(R.id.content_frame, conv).commit();
 } else{
     fragmentManager.beginTransaction().replace(R.id.content_frame, (new Preferences())).commit();
 }
    // update selected item and title, then close the drawer
    mDrawerList.setItemChecked(position, true);
    setTitle(fragments[position]);
    mDrawerLayout.closeDrawer(mDrawerList);
}

當您從活動B返回活動A時,您將重新創建片段,因此它將始終顯示fragment1而不是所需的fragment2。

您的問題是,您信任saveInstanceState來決定是否應該重新創建您的片段。 但是,僅在活動被銷毀時才調用onSaveInstanceState() ,當您導航到下一個活動時,不會立即發生。

如果已經添加了片段,則應該在活動A的onCreate()方法中查詢FragmentManager ,否則將進行初始片段創建。 為了做到這一點,我將添加一個TAG以更好地找到您的片段。

private static final String FRAGMENT_TAG_CONVERSATION = "frag_conv";
...
fragmentManager.beginTransaction().replace(R.id.content_frame, conv, FRAGMENT_TAG_CONVERSATION).commit();

然后,您可以檢查是否已添加片段:

 if(fragmentManager.findFragmentByTag(FRAGMENT_TAG_CONVERSATION) == null))
     // only add it here

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM