1 つのアクティビティと複数のフラグメントのみを含むナビゲーション ドロワーがあります。私のメインフラグメントは読み込みが非常に重いので、メモリに保持しようとします。そうしないと、引き出しを使用すると遅延が発生するからです。
そうするために、私はこのようなレイアウトを持っています:
<RelativeLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
<fragment
android:id="@+id/main_fragment"
android:name=".MainFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
それらは同じ場所ですが、コードではフラグメントレイアウトをより軽いフラグメントに置き換え、メインフラグメントを表示/非表示にします。これは、ドロワー内のアイテムをクリックしたときに呼び出される showFragment メソッドです。
case 0: //Light Fragment
fragment = getSupportFragmentManager().findFragmentByTag("light");
if (fragment == null) {
fragment = ProfileFragment.newInstance();
}
getSupportFragmentManager().beginTransaction().hide(getSupportFragmentManager().findFragmentById(R.id.main_fragment)).commit();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment, "light").addToBackStack(null).commit();
break;
case 1: //Heavy Frag
if (getActiveFragment() != null) {
getSupportFragmentManager().beginTransaction().remove(getActiveFragment()).commit();
}
getSupportFragmentManager().beginTransaction().show(getSupportFragmentManager().findFragmentById(R.id.main_fragment)).addToBackStack(null).commit();
break;
戻るボタンを押した場合を除いて、これは正常に機能します。私は onBackPressed の多くの実装を試みますが、常にメインフラグメントが非表示にする必要があるときに表示され (つまり、2 つのフラグメントが重なり合って)、メインフラグメントが単に表示されないことになります。
おまけの質問: それは正しいやり方ですか? 引き出しが遅れないようにするためですか、それとも実装を完全に変更する必要がありますか?
ありがとう。