【Android】使用ARouter進行畫面遷移的管理

使用ARouter進行畫面遷移的管理

本篇內容是學習筆記,不表明是最好的方案,不保證全部方法的理解正確。
歡迎各位大佬指正,優化。java

1、建立FridgeApplication類

在Application類的onCreate進行ARouter的初始化android

public class FridgeApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        // 若是當前是調試狀態,打開日誌和調試模式
        if (Config.getInstance().isDebug()) {
            ARouter.openLog();
            ARouter.openDebug();
        }

        // 初始化ARouter
        ARouter.init(this);
    }
}

2、修改AndroidManifest.xml文件

增長FridgeApplication類app

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.irisleon.fridge">

    <application
        android:name=".FridgeApplication"   <-- 增長這裏
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.FridgeHelper">
        <activity android:name=".activity.HomeActivity" />
        <activity android:name=".activity.HelloActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

3、在Activity類上增長註解

建立了兩個Activity類,進行標註。爲了保證path不出現拼寫錯誤。此處使用枚舉進行替換。ide

public class ARouterTag {
    public static final String HelloActivity = "/fridge/hello_activity";
    public static final String HomeActivity = "/fridge/home_activity";
}
@Route(path = ARouterTag.HomeActivity)
public class HomeActivity extends AppCompatActivity {
}
@Route(path = ARouterTag.HelloActivity)
public class HelloActivity extends AppCompatActivity {
}

4、進行畫面遷移

  1. 基本的畫面遷移,而且攜帶一份入參,類型是String,名稱是transFromPathpost

    // ARouter進行畫面遷移
    ARouter.getInstance().build("/fridge/home_activity")
        .withString("transFromPath", ARouterTag.HelloActivity)
        .navigation(HelloActivity.this, new NavCallback() {
    
        @Override
        public void onArrival(Postcard postcard) {
            Log.i(TAG, "ARouter has been completed!");
        }
    });
  2. 接受畫面解析畫面遷移的參數學習

    public class HomeActivity extends AppCompatActivity {
    
        // ARouter會自動將transFromPath對應的數據賦值給mTransFromPath。
        // mTransFromPath的訪問權限必須是public。
        @Autowired(name = "transFromPath")
        public String mTransFromPath = "";
    
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_home);
    
            // 解析ARoute提供的參數
            ARouter.getInstance().inject(this);
    
            // 若是遷移時數據正確設定,此處已經能夠取得mTransFromPath
            if (mTransFromPath == "") {
                Log.e(TAG, "ARouter parameter[transFromPath] is unrecognized");
            }
        }
    }
相關文章
相關標籤/搜索