android - addToBackStack() didn't work. Back to home not previous fragment -
i'm pretty new android. when try use addtobackstack()
, encountered problem.
when press button in fragment 2, didn't go fragment 1 home.
why? there wrong in code? thanks!
maiinactivity.java
public class mainactivity extends actionbaractivity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); fragmentmanager mfragmentmanager = getfragmentmanager(); fragmenttransaction mfragmenttransaction = mfragmentmanager.begintransaction(); mfragmenttransaction.add(r.id.id_frame, new firstfrag(), "firstfrag"); mfragmenttransaction.commit(); } }
activity_main.xml
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context="com.example.myfragtest2.mainactivity" > <framelayout android:id="@+id/id_frame" android:layout_width="fill_parent" android:layout_height="fill_parent" ></framelayout> </relativelayout>
firstfrag.java
public class firstfrag extends fragment { private button button1; @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view view = inflater.inflate(r.layout.first_frag, container, false); button1 = (button)view.findviewbyid(r.id.btn1); button1.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { // todo auto-generated method stub fragmentmanager myfragmentmanager = getfragmentmanager(); fragmenttransaction myftransaction = myfragmentmanager.begintransaction(); myftransaction.replace(r.id.id_frame, new secondfrag()); myftransaction.addtobackstack(null); myftransaction.commit(); } }); return view; } }
first_frag.xml
<?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <edittext android:id="@+id/et1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="this frag 1!!" /> <button android:id="@+id/btn1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:text="move frag 2" /> </linearlayout>
add snippet in main activity
@override public void onbackpressed() { if (getfragmentmanager().getbackstackentrycount() == 0) { super.onbackpressed(); } else { getfragmentmanager().popbackstack(); } }
and log count of fragments.
Comments
Post a Comment