android应用框架搭建------BaseActivity
网上有很多介绍BaseActivity的博文,多数是从应用的角度去描述的。
这里,我所介绍的BaseActivity不同,主要从框架搭建的角度去介绍BaseActivity的使用。
先看代码:
/***应用程序Activity的基类**@authorkymjs*@version1.0*@created2013-11-24*/publicabstractclassBaseActivityextendsActivityimplementsOnClickListener{privatestaticfinalintACTIVITY_RESUME=0;privatestaticfinalintACTIVITY_STOP=1;privatestaticfinalintACTIVITY_PAUSE=2;privatestaticfinalintACTIVITY_DESTROY=3;publicintactivityState;//是否允许全屏privatebooleanmAllowFullScreen=true;publicabstractvoidinitWidget();publicabstractvoidwidgetClick(Viewv);publicvoidsetAllowFullScreen(booleanallowFullScreen){this.mAllowFullScreen=allowFullScreen;}@OverridepublicvoidonClick(Viewv){widgetClick(v);}/*****************************************************************************打印Activity生命周期****************************************************************************/@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);AppLog.debug(this.getClass()+"---------onCreat");//竖屏锁定setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);if(mAllowFullScreen){requestWindowFeature(Window.FEATURE_NO_TITLE);//取消标题}AppManager.getAppManager().addActivity(this);initWidget();}@OverrideprotectedvoidonStart(){super.onStart();AppLog.state(this.getClass(),"---------onStart");}@OverrideprotectedvoidonResume(){super.onResume();activityState=ACTIVITY_RESUME;AppLog.state(this.getClass(),"---------onResume");}@OverrideprotectedvoidonStop(){super.onResume();activityState=ACTIVITY_STOP;AppLog.state(this.getClass(),"---------onStop");}@OverrideprotectedvoidonPause(){super.onPause();activityState=ACTIVITY_PAUSE;AppLog.state(this.getClass(),"---------onPause");}@OverrideprotectedvoidonRestart(){super.onRestart();AppLog.state(this.getClass(),"---------onRestart");}@OverrideprotectedvoidonDestroy(){super.onDestroy();activityState=ACTIVITY_DESTROY;AppLog.state(this.getClass(),"---------onDestroy");AppManager.getAppManager().finishActivity(this);}}
定义一个初始化Activity控件的抽象方法initWidget();
像findviewbyid()这类代码就可以写在这里,不会影响代码结构了。这里需要提一点的是:setContent()方法一定要写在initWidget()里,而不能再写到oncreate里面了,看代码可以知道,initwidget方法是存在于super()中的,而如果再写到oncreate里,就相当于先调用了findview再去调用setcontent,这样肯定会报空指针异常。
关于竖屏锁定,这个可以按需要添加,没什么说的。
还有一个要说的就是requestWindowFeature(Window.FEATURE_NO_TITLE); // 取消标题
对于这段代码,如果你要使用系统的ActionBar的时候,一点要记得调用setAllowFullScreen,设置为false,否则BaseActivity自动取消了ActionBar你又去使用,肯定也会出异常。
还有一点:Baseactivity已经实现了OnClickListener,所以子类无需再次实现,控件可以直接在initWidget里面setonclicklistener(this);然后在widgetClick(View v)中设置监听事件即可。
有关AppManager的内容我将放到下一篇《android应用框架搭建》去讲解,这里大家可以先忽略。
有关生命周期的打印,我认为在调试阶段还是有必要的,毕竟看着每一个Activity的生命周期,如果出了问题马上就可以清楚的知道是哪里出了问题。
更多相关文章
- 基于ActionbarActivity中Actionbar自定义布局
- Android(安卓)教程 翻译 1 Activities 活动
- Android(安卓)Studio实现微信摇一摇(传感器)
- listview的使用----BaseAdapter
- IntentService源码解读
- 多重搜索算法_Android多重搜寻,例如传送,搜寻联络人
- Service启动之启动方式和绑定方式
- Wifi定位Gps
- 将获取的html源代码格式化输出