2015-12-29 47 views
0

我有一個FragmentAcivity我正在使用它來創建動態UI。我希望能夠根據FragmentActivity收到的意圖,將僅包含文本的片段替換爲可能必須在線發佈內容的片段,例如Twitter或服務器。在Switch語句中更改片段

我用了一個開關(就像你在下面看到的),Android Studio告訴我它不能解決我的事務對象上的第二個add()(我添加了postFrag)方法。我錯過了什麼?如果使用交換機是一個壞主意,那麼該怎麼辦呢?

'fragView`是片段容器。

private void showContentInContainer() { 

    // Get intent to determine next action 
    int workType = getIntent().getExtras().getInt(MainActivity.TAG_FRAGWORK); 

    FragmentManager fragmentManager = getFragmentManager(); 
    FragmentTransaction transaction = fragmentManager.beginTransaction(); 

    // Add the appropriate frag 
    switch (workType) { 
     case MainActivity.VIEW_RIGHTS : 
      // TODO: Pass a rights fragment 
      RightsFragment rightsFrag = new RightsFragment(); 
      transaction.add(R.id.fragView, rightsFrag); 
      break; 
     case MainActivity.VIEW_SRA : 
      // TODO: Pass a view SRA fragment 
      PostFragment postFrag = new PostFragment(); 
      transaction.add(R.id.fragView, postFrag); 
      break; 
     default: break; 
    } 
    transaction.commit(); // publish changes 
} 

編輯:添加片段容器視圖的XML

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:orientation="vertical" 
android:layout_width="match_parent" 
android:layout_height="match_parent"> 
<ScrollView 
    android:layout_width="match_parent" 
    android:layout_height="0dp" 
    android:layout_weight="1"> 
    <fragment 
     android:id="@+id/fragView" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content"/> 
</ScrollView> 

<fragment 
    android:id="@+id/adFragment_2" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:name="com.frankbrenyahapps.citisafe.adFragment" 
    tools:layout="@layout/fragment_ad" /> 
</LinearLayout> 

回答

1

我的猜測是,postFrag實際上不是片段的一個子類,或者你混了android.support.v4.app.Fragment與android.app.Fragment。 它與switch語句無關。

+0

嗨@Rediska在我的片段容器上,它希望我在編輯過程中有一個佈局,即使我在添加FragmentActivity時動態添加一個佈局。如果我不添加一個活動崩潰,如果我這樣做,我會得到重複的片段。是否因爲我需要一個框架佈局?任何想法如何解決這個問題? – Frank

+0

如果沒有看到代碼很難說出任何內容,但是不需要使用FrameLayout。事實上,你可以在同一個容器中有許多碎片。爲了避免所有亂七八糟的重複片段,我總是使用transaction.replace(id,fragment)。 – Rediska

+0

@Resiska相同的代碼。我的片段只是在onCreate中膨脹它們的佈局(基本上是空的),並且FragmentActivity會在fragView(一個等待填充的空片段元素)中膨脹它們。我更新以顯示我的XML。 – Frank