安卓开发中经常要写一个Activity的抽象基类,以便于将一些基本的功能封装,减少代码量。下面的BaseActivity则是一个非常简单易用的抽象基类。
大家可以根据自己要写的app进行适应性修改。
public abstract class BaseActivity extends AppCompatActivity {
/** 是否状态栏透明 **/
private boolean isSetStatusBar = false;
/** 是否允许全屏 **/
private boolean mAllowFullScreen = false;
/** 是否禁止旋转屏幕 **/
private boolean isAllowScreenRoate = false;
/** 日志输出标志 **/
protected final String TAG = this.getClass().getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "BaseActivity-->onCreate()");
if (mAllowFullScreen) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
}
if (isSetStatusBar) {
steepStatusBar();
}
if (!isAllowScreenRoate) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
/**
* [沉浸状态栏]
*/
private void steepStatusBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// 透明状态栏
getWindow().addFlags(
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// 透明导航栏
getWindow().addFlags(
WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart()");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart()");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume()");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause()");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop()");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy()");
}
/**
* [是否允许全屏]
*
* @param allowFullScreen
*/
public void setAllowFullScreen(boolean allowFullScreen) {
this.mAllowFullScreen = allowFullScreen;
}
/**
* [是否设置沉浸状态栏]
*
* @param isSetStatusBar
*/
public void setSteepStatusBar(boolean isSetStatusBar) {
this.isSetStatusBar = isSetStatusBar;
}
/**
* [是否允许屏幕旋转]
*
* @param isAllowScreenRoate
*/
public void setScreenRoate(boolean isAllowScreenRoate) {
this.isAllowScreenRoate = isAllowScreenRoate;
}