i'm using navigation drawer switch fragments, elements first fragment stay present on changing fragments.
the code of main activity:
protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); ... ... drawer result = new drawerbuilder() .withactivity(this) .withtoolbar(toolbar) .adddraweritems( item1, new dividerdraweritem(), item2, new secondarydraweritem().withname(r.string.drawer_item_settings) ) .withondraweritemclicklistener(new drawer.ondraweritemclicklistener() { @override public boolean onitemclick(view view, int position, idraweritem draweritem) { // clicked item :d fragmentmanager manager = getsupportfragmentmanager(); fragmenttransaction transaction = manager.begintransaction(); fragment fragment = new fragment(); switch (position) { case 0: fragment = new homefragment(); log.d("switch", "search"); break; case 1: break; case 2: fragment = new inventoryfragment(); log.d("switch", "inventory"); break; case 3: fragment = new settingsfragment(); log.d("switch", "settings"); break; } transaction.replace(r.id.main_frame, fragment); transaction.commit(); return false; } }) .build(); }
the following code activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.coordinatorlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitssystemwindows="true" android:background="?android:windowbackground" tools:context="com.example.nihal.xchange.mainactivity"> ... <framelayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:id="@+id/main_frame"> <fragment android:name="com.example.nihal.xchange.homefragment" android:id="@+id/current_fragment" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </framelayout> </android.support.design.widget.coordinatorlayout>
elements home fragment remain present across fragments behavior not exhibited elements of other fragment. how prevent happening?
don't include home fragment in xml. keep container framelayout empty , add initial fragment activity starts. in activity's oncreate method, add home fragment dynamically in beginning.
activity_main.xml -
<framelayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:id="@+id/main_frame"> <!-- removed fragment here --> </framelayout>
in oncreate(), add dynamically -
if (findviewbyid(r.id.main_frame) != null) { if (savedinstancestate != null) return; fragmentmanager manager = getsupportfragmentmanager(); fragmenttransaction transaction = manager.begintransaction(); transaction.add(r.id.main_frame, new homefragment()); transaction.commit(); }
Comments
Post a Comment