我是Android新手,我使用片段。我有活动(MainActivity)和3个片段,A-> B-> C.我需要从C片段返回导航到B,从B导航到A和向后导航。我在Fragment 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();
我找不到任何简单的示例,告诉我如何在片段之间导航,在阅读this article后,我不明白它是如何工作的。 请告诉我,并举例说明我必须如何做到这一点。
答案 0 :(得分:0)
我认为你可以为活动尝试覆盖方法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>