您的位置:首页 > 移动开发 > Android开发

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>


其他用法

待补充
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: