2016-09-15 82 views
1

我在運行時從活動中擴充片段。因此,爲了擡高片段的視圖中的片段I類叫:片段 - 獲取視圖調用onCreateView時出現父錯誤

@Nullable 
    @Override 
    public View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable final Bundle savedInstanceState) { 
    super.onCreateView(inflater, container, savedInstanceState); 
    return inflater.inflate(R.layout.confirm_fragment, container); 
    } 

在這一刻,我得到一個原木崩潰:

Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. 

但是,如果我修改我的方法:

 @Nullable 
     @Override 
     public View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable final Bundle savedInstanceState) { 
     super.onCreateView(inflater, container, savedInstanceState); 
     return inflater.inflate(R.layout.confirm_fragment, null); 
     } 

其中我現在指定我的容器爲null,它的工作原理。但是我不明白的是,在代碼崩潰時,我在哪裏指定了父視圖?

回答

1

this link讀取爲什麼和何時傳遞父容器的實例或在attachToRoot參數中爲null。

從鏈接:

Button button = (Button) inflater.inflate(R.layout.custom_button, mLinearLayout, false); 
mLinearLayout.addView(button); 

通過傳遞虛假的,我們說,我們不希望我們的視圖綁定到根 ViewGroup中,只是還沒有。我們說它會在其他一些時間點發生。在這個例子中,另一個時間點就是在通貨膨脹之後立即使用的addView()方法。

所以,如果你用充氣:

return inflater.inflate(R.layout.confirm_fragment, container); 

首先,它會立即裝confirm_fragment到容器。返回視圖後,片段將嘗試添加到父再次含蓄,但由於它已經被加入,將引發異常:

Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. 

希望你得到了點。

0

您需要設置attachToParentfalse
例子:

inflater.inflate(R.layout.confirm_fragment, container,false); 
+0

是的,如果我指定我的容器爲空,就像我在答案中所做的一樣,它會將attachtoroot作爲false來傳遞。 –

0

嘗試使用下面的代碼:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    View view=inflater.inflate(R.layout.confirm_fragment, container, false); 
    return view; 
} 
+0

是的,如果我指定我的容器爲空,就像我在答案中所做的一樣,它會將attachtoroot作爲false來傳遞。 –

1

在哪裏我指定父爲視圖[.. 。]?

你動態地寫這樣的添加Fragment

FragmentManager fragmentManager = getSupportFragmentManager(); 
FragmentTransaction transaction = fragmentManager.beginTransaction(); 
transaction.add(android.R.id.content, myFragment, FRAGMENT_TAG) 
        .addToBackStack(null) 
        .commit(); 

add(),你指定的Fragment應該將所需容器的id來顯示(在這種情況下全屏)。

又見方法描述在參考developers.android.com

containerViewId INT:容器該片段是被放置在的可選標識符如果爲0,它不會被放置在容器中。

我你不添加Fragment到UI(例如,你需要它的緩存目的的保留片段),onCreateView()將永遠不會被調用。

因此,一旦調用onCreateView(),此Fragment的父級已存在 - FragmentManager已爲您設置。

+0

是的,我是這樣做的。所以add方法自動設置父級? –

+0

@VaibhavSharma - 是的,它的確如此。我添加了一個鏈接到文檔(developer.android.com) – 0X0nosugar

相關問題