简介
博主在大学期间做过web开发,用过struts框架,它能够帮助我们拦截请求,并将事件分发给指定的对象。因此想在Android端实现一个页面跳转的管理器。
项目地址:https://gitee.com/huangbei1990/Dispatcher
其中用到了XMLFactory模块,
如果有不清楚的,请参考我的博客:http://blog.csdn.net/hbdatouerzi/article/details/78252462
使用方法
1.建立xml文件
xml的内容为
<Jumps>
<Jump>
<key>test01</key>
<path>com.example.huangbei.dispatcher.MainActivity</path>
</Jump>
<Jump>
<key>test02</key>
<path>com.example.huangbei.dispatcher.SecondActivity</path>
</Jump>
</Jumps>
其中key是匹配的事件,path是跳转的路径。
2.具体使用
DispatchFactory当中有四个函数可以用于跳转,具体如下
函数 | 参数 | 作用 |
---|---|---|
jump | Context context ,String key | 不传值跳转 |
jump | Context context ,String key ,Bundle bundle | 传值跳转 |
jumpForResult | Context context ,String key ,int requestCode | 不传值需要返回值跳转 |
jumpForResult | Context context ,String key ,Bundle bundle ,int requestCode | 传值需要返回值跳转 |
/*初始化*/
DispatchFactory dispather = DispatchFactory.getInstance();
dispather.init(getAssets().open("jump.xml"));
/*跳转*/
Bundle bundle = new Bundle();//参数
bundle.putString("parameter01","p1");
bundle.putString("parameter02","p2");
bundle.putString("parameter03","p3");
/*this是Activity*/
dispather.jump(this,"test02",bundle);
实现过程
以下是DispatchFactory的源码:
public class DispatchFactory {
private Map<String,String> dispatchPath;
private static DispatchFactory instance;
private Parser parser;
private DispatchFactory(){
dispatchPath = new HashMap<>();
parser = XMLFactory.getPullParser();
}
public static DispatchFactory getInstance(){
if(instance == null){
synchronized (DispatchFactory.class){
if(instance == null){
instance = new DispatchFactory();
}
}
}
return instance;
}
public void init(InputStream inputStream){
try {
List<Jump> list = parser.parse(inputStream, Jump.class);
for(Jump jump : list){
this.dispatchPath.put(jump.getKey(), jump.getPath());
}
}catch(Exception e){
e.printStackTrace();
}
}
public void jump(Context context, String key){
realJump(context,key,null,false,0);
}
public void jump(Context context,String key,Bundle bundle){
realJump(context,key,bundle,false,0);
}
public void jumpForResult(Context context , String key , int requestCode){
realJump(context,key,null,true,requestCode);
}
public void jumpForResult(Context context , String key , Bundle bundle , int requestCode){
realJump(context,key,bundle,true,requestCode);
}
//真正跳转函数
private void realJump(Context context , String key , Bundle bundle , boolean forResult , int requestCode){
String path = dispatchPath.get(key);
if(path == null){
return;
}
try {
Class obj = Class.forName(path);
Intent intent = new Intent(context, obj);
if(bundle != null){
intent.putExtras(bundle);
}
if(forResult == false) {
context.startActivity(intent);
}else{
((Activity)context).startActivityForResult(intent,requestCode);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
init函数从xml文件当中获取跳转规则,并将规则保存为map,当跳转的时候便从map当中通过key来获取跳转的路径。
总结
如果一个App当中页面众多,这样管理起来可以实现页面与页面之间的解耦,但是这一版本只实现了Activity之间的跳转,之后再尝试加入fragment之间跳转的功能。欢迎与我进行讨论。