Android 继承BaseActivity的典型用法
2016-04-18 10:47
756 查看
创建BaseActivity基类的意义
将BaseActivity设置为抽象类或基类,其他Activity子类继承BaseActivity,有以下好处:简化子类代码复杂度
通过继承机制,在基类中封装好默认需实现的共性方法,可以降低子类编写重复代码的工作量,使子类专注于自己的特有功能,也提高了代码可读性、可维护性。强制规范子类行为
通过将BaseActivity设置为抽象类,预定义好需要实现的方法,强制子类实现相关方法,提高代码规范性。以上,也基本上是面向对象思想中的继承机制所带来的好处。
作为UI框架实现页面嵌套
通过在BaseActivity中定义外层界面,子类Activity继承后,可以直接调用父类的方法实现页面嵌套。常见用法
利用Inflater机制实现页面嵌套
得益于Android的Inflater机制,子类中通过Inflater实现对父类中的View的填充,类似于页面嵌套,或者是向UI框架填充相应的内容。例如:BaseActivity中添加方法
public class BaseActivity extends Activity { /** * set screen view * @param layoutResID */ public void baseSetContentView(int layoutResID){ LinearLayout llContent = (LinearLayout) findViewById(R.id.v_content); //v_content是在基类布局文件中预定义的layout区域 //通过LayoutInflater填充基类的layout区域 LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = inflater.inflate(layoutResID, null); llContent.addView(v); } }
当子类继承上面BaseActivity后,可在onCreate中初始化时,将子类的布局文件传入baseSetContentView方法,实现子类+父类布局文件的统一整合。
public class MainActivity extends BaseActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); baseSetContentView(R.layout.act_main); // 其他初始化逻辑…… } }
在BaseActivity对应的布局文件中,需要预留布局区域:
<LinearLayout android:id="@+id/v_content" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> </LinearLayout>
其他用法
待补充相关文章推荐
- Android Studio 下安卓 jni 开发错误 undefined reference to __android_log_print
- android 防止Button的频繁点击,多次执行点击事件
- Android 分享一个SharedPreferences的工具类,方便保存数据
- 一套效果图适配(Android和IOS)全尺寸和标注规范-(结果)
- android studio 快捷键大全
- android handler的警告Handler Class Should be Static or Leaks Occur
- 【day0418 Android】1. 使用Android的日志工具Log
- 加速Android Studio的Gradle构建速度
- android studio 2.0 下创建JNI应用
- Android dp2px
- android 特殊用户通知用法汇总--Notification源码分析
- 首款Ubuntu手机BQ-Aquaris E4.5刷安卓教程
- Android相关权限的概念
- Android中Activity的生命周期
- Android Viewbadger 实现消息数字提示
- 关于 Android 进程保活,你所需要知道的一切
- 【转载】 android 圆角圆形图片ShapedImageView不到100行代码
- Android里Service的bindService()和startService()混合使用深入分析
- Android应用程序(APK)的编译打包过程
- Android ViewDragHelper(1)