我正在尝试实现Jetpack Navigation,我有两个片段。我想在第二个片段的工具栏中添加后退按钮,当我点击它时,我希望它导航回第一个片段。
fragment_fragment1.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment 1"
android:textSize="25dp"/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Navigate to 2nd Fragment"/>
fragment1.Java
public class Fragment1 extends Fragment {
private Button button;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_fragment1, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
button = view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Navigation.findNavController(v).navigate(R.id.action_fragment1_to_fragment2);
}
});
}
}
fragment_fragment2
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment 2"
android:textSize="25dp"/>
fragment2.Java
public class Fragment2 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment2, container, false);
}
}
在您的活动中,您需要使用工具栏设置navController。如果您使用的是自定义工具栏,则可以通过调用Navigation.setupWithNavController(toolbar, navController)
来完成。相反,如果您正在使用默认的actionBar of activity,则需要启用setDisplayHomeAsUpEnabled(true)
,而在optionItemSelected
中,您需要在单击向上时执行navigateUp。