2015-11-02 67 views
1

我不能代替片段是這樣的:在第一加入是否可以替換使用佈局XML創建的片段?

A2Fragment a2Fragment = new A2Fragment(); 
FragmentTransaction transaction = getChildFragmentManager().beginTransaction(); 
transaction.addToBackStack(null); 
transaction.replace(R.id.fragment_mainLayout, a2Fragment).commit(); 

第二片段。我已經嘗試了很多解決方案,但總是發生同樣的情況。我現在讀到,不可能替換從佈局XML文件添加的片段,並且它應該以編程方式添加,以便可以替換它。這是真的?

我現在在onCreateView中嘗試了這一點,並開始工作。

Context context = getActivity(); 
LinearLayout base = new LinearLayout(context); 
base.setOrientation(LinearLayout.VERTICAL); 
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); 
base.setLayoutParams(params); 
TextView text = new TextView(context); 
text.setGravity(Gravity.CENTER); 
String title; 
text.setText("Pager: "); 
text.setTextSize(20 * getResources().getDisplayMetrics().density); 
text.setPadding(20, 20, 20, 20); 
params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); 
text.setLayoutParams(params); 
FrameLayout layout = new FrameLayout(getActivity()); 
layout.setId(fragmentId); 
params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0); 
params.weight = 1; 
layout.setLayoutParams(params); 
layout.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View view) { 
     FragmentManager manager = getFragmentManager(); 
     FragmentTransaction transaction = manager.beginTransaction(); 
     transaction.replace(fragmentId,new A2Fragment()); 
     transaction.addToBackStack(null); 
     transaction.commit(); 
    } 
}); 
layout.addView(text); 
base.addView(layout); 
return base; 
+1

爲什麼不直接使用FrameLayout裏包含您的片段爲兩個片段?初始化您的活動以最初顯示一個片段,然後當您想要顯示第二個片段時,按照上述說明進行操作? –

+0

我已經試過這個,我得到了同樣的結果。第二個出現在第一個。 –

+0

您應該使用getSupportFragmentManager()在您的活動中執行所有片段事務,而不是在Fragment中執行事務,因爲它看起來像您在上面做的那樣。當然,除非你的目標是顯示片段本身的一個片段 –

回答

1

您可以在xml中創建一個片段,然後以編程方式將其替換。

  1. 創建XML。這個XML只包含一個片段。您可以使用通過引用其完全限定的類名創建的片段。

    <RelativeLayout 
        xmlns:android="http://schemas.android.com/apk/res/android" 
        android:layout_width="match_parent" 
        android:layout_height="match_parent" > 
    
        <fragment 
         android:id="@+id/fragment_container" 
         android:layout_centerHorizontal="true" 
         android:layout_width="match_parent" 
         android:layout_height="match_parent" 
         android:name="com.yourorg.fragment.EmptyFragment" /> 
    
    </RelativeLayout> 
    
  2. 使用片段事務來更改片段。

    public void swapContentFragment(Fragment fragment) { 
    
        FragmentTransaction transaction = mFragmentManager.beginTransaction(); 
        transaction.replace(R.id.fragment_container, fragment, "tagname"); 
        transaction.addToBackStack("tagname"); 
        transaction.commitAllowingStateLoss(); 
    } 
    
相關問題