IntentLife框架幫助您輕鬆愉快地接收Intent數據

一般情況下,我們在一個Activity中接收上一個Activity傳遞的Intent攜帶的數據會寫一堆getXXXExtra方法,需要傳入key值,還要寫強轉代碼,想想都覺得噁心…

於是本文推出IntentLife來幫助大家減少繁重的開發工作

IntentLife框架地址:https://github.com/ausboyue/IntentLife

一個自動綁定Intent攜帶的數據的android庫。(An android library that automatically binds data carried by the Intent.)

如何使用

簡述使用流程:

添加IntentLife依賴
綁定當前Activity
屬性添加BindIntentKey註解

一、引用框架

1. 在項目根目錄下的build.gradle添加倉庫地址:

    allprojects {
        repositories {
            ...
            maven { url 'https://jitpack.io' }
        }
    }

2. 在需要使用框架的Module下的build.gradle添加依賴:

    dependencies {
          implementation 'com.github.ausboyue.IntentLife:intentlife:v1.0.0'
          annotationProcessor 'com.github.ausboyue.IntentLife:intentlife_compiler:v1.0.0'
    }

二、開始使用

1. ActivityA跳轉ActivityB

  • ActivityA跳轉代碼可能如下:
        User user = new User();
        user.setUserId("9527");
        user.setName("Cheny");
        user.setJob("android developer");

        Intent intent = new Intent(activityA, ActivityB.class);
        intent.putExtra("key_user", user);
        startActivity(intent);
  • ActivityB中在需要綁定數據的屬性上加IntentLife註解(@BindIntentKey),如:
    @BindIntentKey("key_user")
    User mUser;
  • 在ActivityB的onCreate方法中適當位置綁定當前Activity,完整代碼如下:
    public class ActivityB extends AppCompatActivity {
        @BindIntentKey("key_user")
        User mUser;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_secend);
            //  IntentLife inject
            IntentLife.bind(this);
            
            TextView tv_user_name = findViewById(R.id.tv_user_name);
            tv_user_name.setText(
                    "Hello , I am " + mUser.getName()
                            + ".\nMy job is " + mUser.getJob() + ".");
        }
    }

這樣就可以直接對mUser進行操作了。

建議將綁定代碼IntentLife.bind(this)寫在基礎的Activity中(如BaseActivity),一勞永逸。

框架支持

數據類型

  • 支持java八大基本數據類型及其數組和集合
  • 支持實現java序列化Serializable接口的類
  • 支持實現android序列化Parcelable接口的類及其數組和集合
  • 下個版本支持Bundle數據

界面場景

  • 支持Activity間的跳轉
  • 下個版本支持加載Fragment

使用注意

需要的綁定的屬性不應有private修飾,否則無法正常綁定數據。

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