单Activity架构,丝滑般享受

来源:互联网 发布:mac 制作3d模型软件 编辑:程序博客网 时间:2024/05/17 04:28

注:自己写的手记,取下来整理到博客中,让更多人能方便看到

大多数正在学习的同学,往往是从Activity的生命周期以及Activity间的跳转开始展开学习的。而大部分的Android应用,其业务逻辑的分割或者场景的转换也是基于Activity进行的。
首先,这是属于绝对中规中矩的做法,毕竟,Activity起初的设计也是以分割逻辑,跳转页面为基础的。但是呢,自从Google推出了Fragment之后,这种观念正在逐渐的被淡化,以至于,现在很多市面上流行的App都是基于多Activity+多Fragment架构,更有甚者,干脆抛弃了Activity的跳转,采用单Activity+多Fragment架构
这种模式的好处显而易见。Fragment比Activity占用少得多的系统资源,特别是在中低端手机上,Fragment的响应速度相较于Activity成倍的提高。对于灵活性,因为Fragment是一个个的碎片,所以我们更容易控制每个场景的生命周期和状态,比 Activity的灵活性大了很多。并且,当我们的App想要移植到平板上时,Fragment会大大减少我们的开发量。
当然啦,Fragment的坑也是巨多的。空指针,显示异常,过渡动画,返回栈等都是Fragment的问题,好在Github上的巨人足够的多,让我们得以站在巨人的肩膀上成长。
我比较喜欢使用的一个“巨人”,是Github上的一个开源项目Fragmentation,链接在这里https://github.com/YoKeyword/Fragmentation
在Fragmentation的基础上,我结合了ButterKnife进行了一些简单的封装,比如我们可以创建一个简单的抽象类基础代理,实现ISupportFragment接口,然后做些基本封装

    @SuppressWarnings("SpellCheckingInspection")    private Unbinder mUnbinder = null;    public abstract Object setLayout();    public abstract void onBindView(@Nullable Bundle savedInstanceState, View rootView);

这些抽象方法强制使用的子类去实现,来达到强制传值的目的

@Nullable    @Override    public View onCreateView(LayoutInflater inflater,                             @Nullable ViewGroup container,                             @Nullable Bundle savedInstanceState) {        final View rootView;        if (setLayout() instanceof Integer) {            final int layoutResId = (int) setLayout();            rootView = inflater.inflate(layoutResId, container, false);        } else if (setLayout() instanceof View) {            rootView = (View) setLayout();        } else {            throw new ClassCastException("typeof setLayout() must be int or View!");        }        mUnbinder = ButterKnife.bind(this, rootView);        onBindView(savedInstanceState, rootView);        return rootView;    }

同时在onCreateView方法种进行初始化,那这样的话,子类就可以在ButterKnife绑定了试图后,直接在onBindView中进行操作了
既然我们是单Activity架构,那么我们也需要一个容器Activity

 public abstract LatteDelegate setRootDelegate();    @Override    protected void onCreate(@Nullable Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        ActionBar actionBar =getSupportActionBar();        if (actionBar != null) {            actionBar.hide();        }        initContainer(savedInstanceState);    }    private void initContainer(@Nullable Bundle savedInstanceState) {        final FrameLayout container = new FrameLayout(this);        container.setId(R.id.delegate_container);        container.setFitsSystemWindows(true);        setContentView(container);        if (savedInstanceState == null) {            loadRootFragment(R.id.delegate_container, setRootDelegate());        }    }

通过这样的简单处理,我们就可以在容器Activity中进行各种Fragment的跳转了。特别的,LatteDelegate是我在我的《Android通用框架设计与完整电商APP开发》
这样,我们大体的应用结构,就确定为,单Activity+多Fragment结构了


相关文章

《关于Android高性能Restful请求的通用封装(单Retrofit和Retrofit+RxJava)》

《在慕课网授课后关于学习模式的实践和思考》

作者: 傅猿猿 
链接:http://www.imooc.com/article/18845
来源:慕课网
本文原创发布于慕课网 ,转载请注明出处,谢谢合作!

视频链接 《Abdroid通用框架设计与完整电商App开发》 

原创粉丝点击