我是Android的新手,我使用片段。我有活动(主活动)和 3 个片段,A->B->C。我需要从 C 片段向后导航到 B,从 B 到 A 并向后导航。我在片段 A 看到 A,点击 B 看到 B,点击 C 看到 C,但是当我点击返回时,我的应用程序被关闭了。为什么?这里有一个例子,我称之为片段
Fragment Subcategory = new Subcategory();
Bundle bundle = new Bundle();
bundle.putInt("id", i);
String title = dba.getTitle(i,true);
bundle.putString("title", title);
Subcategory.setArguments(bundle);
FragmentTransaction transaction_cat = getFragmentManager().beginTransaction();
transaction_cat.replace(R.id.fragment_container, Subcategory);
transaction_cat.addToBackStack(null);
transaction_cat.commit();
我找不到任何简单的例子来展示如何在片段之间导航,阅读本文后我不明白它是如何工作的。请告诉我,并写下我必须如何做到这一点的例子。
我认为您可以尝试覆盖活动的方法onBackPressed()
。
更新:
这是我代码的一部分。
public class MainActivity extends Activity {
RelativeLayout mContainer;
int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContainer = (RelativeLayout) findViewById(R.id.fragment_container);
addFragment();
}
private void addFragment() {
FragmentManager fm = getFragmentManager();
Fragment f = fm.findFragmentById(R.id.fragment_container);
if (f == null) {
f = new MainActivityFragment();
f.setArguments(getIntent().getExtras());
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment_container, f);
ft.addToBackStack("" + count++);
ft.commit();
}
}
private void replaceFrament() {
FragmentManager fm = getFragmentManager();
Fragment f;
f = new BlankFragment();
f.setArguments(getIntent().getExtras());
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_container, f);
ft.addToBackStack("" + count++);
ft.commit();
}
public void onAddFragmentClick(View v) {
replaceFrament();
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
}
<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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivityFragment">
<RelativeLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"></RelativeLayout>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add Fragment"
android:layout_alignParentBottom="true"
android:onClick="onAddFragmentClick"/>
</RelativeLayout>