Android 官方組件 Navigation(附Java版、Kotlin版)

Navigation—Java版

Google 2018 I/O大會上,谷歌隆重推出一個新的架構組件:Navigation。從名字上可以看出他是一個導航,其實我們可以把它理解爲FragmentNavigation。它提供了多Fragment之間的轉場,棧管理,幫助你更輕鬆的使用Fragment。在以後抽屜式導航欄,底部、頂部導航欄的需求中我們可以嘗試使用這個新組件。甚至,你可以嘗試寫一個單Activity的應用。

下面是我寫的一個Sample,我將引導大家去實現這個小功能。
在這裏插入圖片描述
使用 Navigation 需要 AndroidStudio的版本3.2以上

第一步:創建兩個Fragment,FristFragment和SecondFragment

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
    tools:context=".FirstFragment">
 
    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_marginTop="100dp"
        android:layout_gravity="center_horizontal"
        android:text="我是第一個Fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
 
    <Button
        android:textAllCaps="false"
        android:id="@+id/btn_next"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="跳轉到第二個Fragment" />
 
</FrameLayout>
<FrameLayout 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:orientation="vertical"
    tools:context=".SecondFragment">
 
    <!-- TODO: Update blank fragment layout -->
 
    <TextView
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="100dp"
        android:text="我是第二個Fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
 
    <Button
        android:layout_gravity="center"
        android:id="@+id/btn_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="返回" />
 
</FrameLayout>

第二步:創建導航視圖文件

在res目錄下新建navigation文件夾,然後新建一個navigation資源文件(需要AndroidStudio3.2以上版本)
在這裏插入圖片描述
打開資源文件,切換爲design可視化編輯模式,在這個界面,我們可以任意添加Fragment和Activity,用箭頭線連接它們,就爲它們綁定了跳轉事件。
在這裏插入圖片描述
切換爲Text模式,下面就是自動編輯好的代碼。action標籤描述的Fragment轉場事件,在裏面我們除了可以設置目標Fragment之外,還可以設置轉場動畫和啓動模式。

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    app:startDestination="@id/firstFragment">
 
    <fragment
        android:id="@+id/firstFragment"
        android:name="com.example.navigation.FirstFragment"
        android:label="fragment_first"
        tools:layout="@layout/fragment_first" >
        <action
            android:id="@+id/action_firstFragment_to_secondFragment"
            app:destination="@id/secondFragment" />
    </fragment>
    <fragment
        android:id="@+id/secondFragment"
        android:name="com.example.navigation.SecondFragment"
        android:label="fragment_second"
        tools:layout="@layout/fragment_second" >
    </fragment>
</navigation>

第三步:編輯MainActivity

在Acitvity佈局文件中添加fragment組件,設置name屬性爲androidx.navigation.fragment.NavHostFragment。在傳統的單Activity多Fragment場景中,我們往往需要爲Activity添加一個FrameLayout作爲Fragment的容器。在Navigation中HavHostFragment就是Fragment的容器。佈局中的navGraph屬性建立了與navigation資源文件的關係。

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
   <fragment
       android:name="androidx.navigation.fragment.NavHostFragment"
       android:id="@+id/fragment"
       android:layout_width="0dp"
       android:layout_height="0dp"
       app:layout_constraintBottom_toBottomOf="parent"
       app:layout_constraintLeft_toLeftOf="parent"
       app:layout_constraintRight_toRightOf="parent"
       app:layout_constraintTop_toTopOf="parent"
       app:defaultNavHost="true"
       app:navGraph="@navigation/nav_fragment" />
 
</android.support.constraint.ConstraintLayout>

重寫onSupportNavigateUp()方法,目的是將back事件委託出去。若棧中有兩個以上Fragment,點擊back鍵就會返回到上一個Fragment。

public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
 
    @Override
    public boolean onSupportNavigateUp() {
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment);
        return NavHostFragment.findNavController(fragment).navigateUp();
    }
}

第四步:在Fragment中設置相應的跳轉事件。

public class FirstFragment extends Fragment {
 
 
    public FirstFragment() {
        // Required empty public constructor
    }
 
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false);
    }
 
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Button btnNext = view.findViewById(R.id.btn_next);
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Navigation.findNavController(v).navigate(R.id.action_firstFragment_to_secondFragment);
            }
        });
    }
}
public class SecondFragment extends Fragment {
 
 
    public SecondFragment() {
        // Required empty public constructor
    }
 
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_second, container, false);
    }
 
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Button btnBack = view.findViewById(R.id.btn_back);
        btnBack.setOnClickListener(new View.OnClickListener(){
 
            @Override
            public void onClick(View v) {
                Navigation.findNavController(v).navigateUp();
            }
        });
    }
}

可以看到,關鍵API就是一行,界面切換如此簡單。如果需要傳值,把數據設置在Bundle中,使用以下api即可

Navigation.findNavController(view).navigate(actionid,bundle);

至此,我們就可以把程序運行起來。如果需要添加轉場動畫,需要在navigation資源文件的action標籤下,添加動畫屬性。

<action
            app:enterAnim="@anim/slide_in_right"
            app:exitAnim="@anim/slide_out_left"
            app:popEnterAnim="@anim/slide_in_left"
            app:popExitAnim="@anim/slide_out_right"
            android:id="@+id/action_firstFragment_to_secondFragment"
            app:destination="@id/secondFragment" />

Navigation—Kotlin版

  Android官方架構組件Navigation:大巧不工的Fragment管理框架

理解Navigation

  詳細理解Navigation

最後

  哇!跳轉,傳值,管理棧,還有轉場動畫!簡直跟Activity的使用一模一樣。從此,Fragment除了擁有自身的優點之外,還get了Activity的技能,我們在構建App的時候是不是可以更加肆意得使用Fragment呢?
 
參考:
  Android官方架構組件Navigation:大巧不工的Fragment管理框架

  手把手教你使用Android官方組件Navigation
 
推薦文章:
  Android-Jetpack筆記-Navigation之Fragment使用

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章