本文介绍了一种优美写Intent的方式,能够在项目开发中遵循这种开发规则java
该系列文章会不断更新Android项目开发中一些好的架构和小技巧android
系列一 Android架构系列-基于MVP建立适合本身的架构
系列二 Android架构系列-如何优美的写Intent
系列三 Android架构系列-开发规范
系列四 Android架构系列-封装本身的okhttp
系列五 Android架构系列-MVP架构的实际应用架构
普通activity a要调用起activity b页面会这么写:
activity a框架
Intent intent = new Intent(a.this, b.class);
intent.putExtra("is_index", message);
startActivity(intent);复制代码
activity bide
@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。post
so,根据以上问题,无心间看到了google官方example代码里一个使用intent的小技巧。优化
一样是activity a要调用起activity b页面的例子:this
Intent intent = b.newIndexIntent(this, text);
startActivity(intent);复制代码
activity bgoogle
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有详细的注释(是否必须、在什么地方调用)spa
好的项目架构每每是清晰的大框架加上某些优美的小细节,后续继续整理,未完待续...
更多文章关注个人公众号