簡體   English   中英

替換的片段在新片段的后面仍然可見

[英]Replaced fragment still visible behind new fragment

我嘗試實現一種活動,該活動可以將不同的片段加載到一個容器視圖元素中。 我遵循構建靈活的UI培訓 問題:替換片段時,我仍然可以在后台看到替換的片段。

我看到我的問題已經被問過無數次了。 但是,我發現的所有答案似乎都只是一種解決方法(設置片段的背景顏色)或不適用。

到目前為止,這是我設置的內容:

活動的XML布局包含一個FrameLayout作為片段的容器:

<FrameLayout
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

該ID fragment_container不能用於其他地方的項目。

第一個片段的完整XML布局:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="First Fragment" />

第二個片段的完整XML布局:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textColor="#ff0000"
    android:text="Fragment Second" />

第一個片段的類文件如下所示(第二個片段的類類似):

public class FirstFragment extends Fragment {

    public FirstFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_first, container, false);
    }

}

在活動的onCreate方法中,我加載第一個片段:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // load first fragment
    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, new FirstFragment())
                .commit();
    }
}

在選擇菜單項時,我嘗試使用活動的onOptionsItemSelected方法中的以下代碼將第一個片段替換為第二個片段:

getFragmentManager().beginTransaction()
        .replace(R.id.fragment_container, new SecondFragment())
        .addToBackStack(null) // <-- does not make any difference if left out
        .commit();

結果是文本“ Fragment Second”以紅色打印在文本“ First Fragment”上方。

解決此問題的“正確方法”是什么(即不僅設置背景顏色)?

我在onCreate注意到了這一點:

        getSupportFragmentManager()

這在onOptionsItemSelected

        getFragmentManager()

實際上, AppCompatActivity中有FragmentManager兩個版本,彼此之間一無所知。 所以,當你告訴android.app.FragmentManager以替換被添加片段android.support.v4.app.FragmentManager ,它不知道一個東西FirstFragment所以操作更像一個比一個替代加。

我已經多次犯了這個錯誤。 您需要梳理代碼,並確保在使用支持類與常規類方面保持一致。

暫無
暫無

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

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