Android架构系列-如何优美的写Intent

本文介绍了一种优美写Intent的方式,可以在项目开发中遵循这种开发规则

0 Android架构系列文章

该系列文章会不断更新Android项目开发中一些好的架构和小技巧

系列一 Android架构系列-基于MVP创建适合自己的架构
系列二 Android架构系列-如何优美的写Intent
系列三 Android架构系列-开发规范
系列四 Android架构系列-封装自己的okhttp
系列五 Android架构系列-MVP架构的实际应用

1 普通写Intent的方法和缺陷

普通activity a要调用起activity b页面会这么写:
activity a

Intent intent = new Intent(a.this, b.class);
intent.putExtra("is_index", message);
startActivity(intent);复制代码

activity b

@Override
protected void onCreate(Bundle savedInstanceState) {        
    super.onCreate(savedInstanceState);
    ...
    String is_index = getIntent().getExtras().getString("is_index");
    ...
}复制代码

上面的写法是大多数Intent写法,在发起方创建intent。但这种写法在代码量大大增加的时候会出现一个问题。当activity b在各种地方都会被调用起的时候,并且会传入各种各样不同的extra字段时,会发现很混乱,哪些发起方使用了哪些extra字段,每个字段什么意思,哪些是必须的等等问题。最终造成b代码可读性变差,让以后想要调用起b的页面也不清楚需要传入哪些extra。

so,根据以上问题,无意间看到了google官方example代码里一个使用intent的小技巧。

2 优化写Intent

同样是activity a要调用起activity b页面的例子:

Intent intent = b.newIndexIntent(this, text);
startActivity(intent);复制代码

activity b


private final static String IS_INDEX = "is_index";

@Override
protected void onCreate(Bundle savedInstanceState) {        
    super.onCreate(savedInstanceState);
    ...
    String is_index = getIntent().getExtras().getString(IS_INDEX);
    ...
}

...

/**
 * 创建intent
 * is_index 是否是首页跳转过来的 
 */
public static Intent newIndexIntent(Context context, String message) {
        Intent newIntent = new Intent(context, b.class);
        newIntent.putExtra(IS_INDEX, message);
        return newIntent;
    }复制代码

用上面的方法可以保证所有extra全部定义在被调用起activity的内部,对外不可见,并可以对每个extra有详细的注释(是否必须、在什么地方调用)

结尾

好的项目架构往往是清晰的大框架加上某些优美的小细节,后续继续整理,未完待续...

更多文章关注我的公众号

我的公众号

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值