Android 네비게이션 뒤로가기

timothy jeong·2021년 12월 3일
0

Android with Kotlin

목록 보기
56/69

백 스택

안드로이드 앱에서 여러 뷰를 이동하면 안드로이드 시스템은 사용자가 이동한 화면을 백스택에 쌓아둔다. 백스택은 유저가 방문한 화면에 대한 로그이다. 네비게이션의 destination 을 이동할때마다 안드로이드 시스템은 이 destination 을 백스택 최상단에 쌓아둔다. 그리고 back button 을 누를때마다 최상단을 pop 하고 바로 밑의 화면을 스크린에 띄운다.

POP behavior

pop behavior 를 재정의함으로써 뒤로가기 버튼을 눌렀을때 백스택에 대한 행동을 변경할 수 있다. 이전의 예시로 치면 ThreeFragment 에서 뒤로 가기를 누르면 OneFragment 가 나오도록 만들어보자

네비게이션 그래프에서 설정할 수 있다.

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/nav_graph"
    app:startDestination="@id/oneFragment">

    <fragment
        android:id="@+id/oneFragment"
        android:name="com.example.test.OneFragment"
        android:label="OneFragment" >
        <action
            android:id="@+id/toTwoFragment"
            app:destination="@id/twoFragment" />
    </fragment>

    <fragment
        android:id="@+id/twoFragment"
        android:name="com.example.test.TwoFragment"
        android:label="TwoFragment" >
        <action
            android:id="@+id/toThreeFragment"
            app:destination="@id/threeFragment"
            app:popUpTo="@id/oneFragment"/>
    </fragment>

    <fragment
        android:id="@+id/threeFragment"
        android:name="com.example.test.ThreeFragment"
        android:label="ThreeFragment">
        <action
            android:id="@+id/toFirst"
            app:destination="@id/oneFragment" />
    </fragment>
</navigation>

twoFragment 부분에서 app:popUpTo="@id/oneFragment" 을 설정함으로써, twoFragment 로 돌아오면 oneFragment 로 돌아가게끔 설정했다.

profile
개발자

0개의 댓글