在实际的开发当中,我们总是会用到很多公用的方法,可能我们习惯性的给封装成一个公用的代码块方法,但其实开发一个APP来说,界面的交互都是通过activity和fragment来构造的,所以我们不妨封装一个通用的activity和fragment父类,让所有的activity和fragment都集成其中,而在使用这些通用的方法的时候也方便我们直接去引用
封装的方法有很多,但基本上都是大同小异,这里我们去使用viewBing,没有原因,因为喜欢,哈哈哈,那什么是viewBinding呢?没有比官方文档更详细的介绍了,有兴趣的话可以具体的看看
View Binding是Android Studio 3.6推出的新特性,目的是为了替代findViewById(内部实现还是使用findViewById)。。在启动视图绑定后,系统会为改模块中的每个xml文件生成一个绑定类,绑定类的实例包含对在相应布局中具有 ID 的所有视图的直接引用。
View Binding 的优点
1、Null 安全:由于视图绑定会创建对视图的直接引用,因此不存在因视图 ID 无效而引发 Null 指针异常的风险。此外,如果视图仅出现在布局的某些配置中,则绑定类中包含其引用的字段会使用 @Nullable 标记。
2、类型安全:每个绑定类中的字段均具有与它们在 XML 文件中引用的视图相匹配的类型。这意味着不存在发生类转换异常的风险。
接下来就是进行我们的封装方法了,首先需要在我们的项目去启用viewBinding
android{
//使用viewBinding
buildFeatures {
viewBinding = true
}
}
然后就是封装我们的基类了,从官方的来说其实很简单
protected VB binding;
binding = getViewBinding();
setContentView(binding.getRoot());
其实总体来说只有三行代码,其他的便是我们自己的拓展功能,这里不做过多赘述,直接上干货
BaseActivity
public abstract class BaseAppCompatActivity<VB extends ViewBinding> extends AppCompatActivity
implements View.OnClickListener {
public static final int NON_CODE = -1;
/*获取屏幕信息*/
protected int mScreenWidth = 0;
protected int mScreenHeight = 0;
protected float mScreenDensity = 0.0f;
protected Context mContext = null;
protected ImmersionBar mImmersionBar;
protected VB binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//传参
Bundle extras = getIntent().getExtras();
if (null != extras) {
getBundleExtras(extras);
}
//注册EventBus
if (isBindEventBusHere()) {
EventBus.getDefault().register(this);
Log.e("eventBus", "register");
}
mContext = this;
// 加入到Activity栈
BaseAppManager.getInstance().addActivity(this);
/* 获取屏幕信息 */
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
mScreenDensity = displayMetrics.density;
mScreenHeight = displayMetrics.heightPixels;
mScreenWidth = displayMetrics.widthPixels;
if (isImmersionBarEnabled()) {
initImmersionBar();
}
binding = getViewBinding();
setContentView(binding.getRoot());
if (hasTitleBar()) {
setCustomTitle(getTitle());
onTitleBarBackClick();
}
initViewsAndEvents();
addListener();
}
protected void initImmersionBar() {
mImmersionBar = ImmersionBar.with(this);
mImmersionBar.init();
if (ImmersionBar.isSupportStatusBarDarkFont())
mImmersionBar.statusBarDarkFont(true).keyboardEnable(true).init();
}
//绑定标题栏
protected boolean hasTitleBar() {
return findViewById(R.id.title_bar) != null;
}
//设置标题title
protected void setCustomTitle(CharSequence title) {
if (hasTitleBar()) {
TextView titleView = findViewById(R.id.title_tv_message);
if (titleView != null) {
titleView.setText(title);
setTitle("");
}
}
}
//获取标题栏返回键
protected void onTitleBarBackClick() {
if (hasTitleBar()) {
ImageButton backView = findViewById(R.id.actionbar_back);
if (backView != null) {
backView.setOnClickListener(v -> finish());
}
}
}
/**
* 是否可以使用沉浸式
*/
protected boolean isImmersionBarEnabled() {
return true;
}
/**
* bind layout resource file
*/
protected abstract VB getViewBinding();
/**
* init activity view and bind event
*/
protected abstract void initViewsAndEvents();
/**
* 是否注册EventBus
*/
protected boolean isBindEventBusHere() {
return false;
}
protected void getBundleExtras(Bundle extras) {
}
/**
* 给 View 控件添加点击事件监听器
*/
protected void addListener() {
}
/**
* view的点击事件
* 屏蔽快速点击而引发的问题
*/
protected void onWidgetClick(View view) {
}
private long lastTime = 0L;
private View currentView = null;
@Override
public void onClick(View view) {
long nowTime = System.currentTimeMillis();
if (nowTime - lastTime > 1000L || view.getId() == currentView.getId()) {
lastTime = nowTime;
currentView = view;
onWidgetClick(view);
}
}
/**
* startActivity
*
* @param clazz target Activity
*/
protected void go(Class<? extends Activity> clazz) {
_goActivity(clazz, null, NON_CODE, false);
}
/**
* startActivity with bundle
*
* @param clazz target Activity
*/
protected void go(Class<? extends Activity> clazz, Bundle bundle) {
_goActivity(clazz, bundle, NON_CODE, false);
}
/**
* startActivity then finish this
*
* @param clazz target Activity
*/
protected void goAndFinish(Class<? extends Activity> clazz) {
_goActivity(clazz, null, NON_CODE, true);
}
/**
* startActivity with bundle and then finish this
*
* @param clazz target Activity
* @param bundle bundle extra
*/
protected void goAndFinish(Class<? extends Activity> clazz, Bundle bundle) {
_goActivity(clazz, bundle, NON_CODE, true);
}
/**
* startActivityForResult
*/
protected void goForResult(Class<? extends Activity> clazz, int requestCode) {
_goActivity(clazz, null, requestCode, false);
}
/**
* startActivityForResult with bundle
*/
protected void goForResult(Class<? extends Activity> clazz, Bundle bundle, int requestCode) {
_goActivity(clazz, bundle, requestCode, false);
}
/**
* startActivityForResult then finish this
*/
protected void goForResultAndFinish(Class<? extends Activity> clazz, int requestCode) {
_goActivity(clazz, null, requestCode, true);
}
/**
* startActivityForResult with bundle and then finish this
*/
protected void goForResultAndFinish(Class<? extends Activity> clazz, Bundle bundle, int requestCode) {
_goActivity(clazz, bundle, requestCode, true);
}
@Override
public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
}
@Override
public void finish() {
super.finish();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
}
BaseAppManager.getInstance().removeActivity(this);
}
@Override
protected void onDestroy() {
if (isBindEventBusHere()) {
EventBus.getDefault().unregister(this);
Log.e("eventBus", "unregister");
}
if (mImmersionBar != null) {
mImmersionBar.destroy();
}
BaseAppManager.getInstance().removeActivity(this);
super.onDestroy();
}
/**
* Activity 跳转
*
* @param clazz 目标activity
* @param bundle 传递参数
* @param finish 是否结束当前activity
*/
private void _goActivity(Class<? extends Activity> clazz, Bundle bundle, int requestCode, boolean finish) {
if (null == clazz) {
throw new IllegalArgumentException("you must pass a target activity where to go.");
}
Intent intent = new Intent(this, clazz);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
if (null != bundle) {
intent.putExtras(bundle);
}
if (requestCode > NON_CODE) {
startActivityForResult(intent, requestCode);
} else {
startActivity(intent);
}
if (finish) {
finish();
}
}
}
BaseFragment
public abstract class BaseFragment<VB extends ViewBinding> extends Fragment
implements View.OnClickListener {
private static final int NON_CODE = -1;
protected Context mContext;
protected VB binding;
//加载布局
protected abstract VB getViewBinding(LayoutInflater inflater, ViewGroup viewGroup);
protected abstract void initViewsAndEvents();
/*是否绑定eventbus事件* */
protected boolean isBindEventBusHere() {
return false;
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
mContext = context;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (isBindEventBusHere()) {
EventBus.getDefault().register(this);
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = getViewBinding(inflater, container);
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//屏幕适配
DisplayMetrics displayMetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
initViewsAndEvents();
addListener();
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (isBindEventBusHere()) {
EventBus.getDefault().unregister(this);
}
}
/**
* 给 View 控件添加点击事件监听器
*/
protected void addListener() {
}
protected void onWidgetClick(View view) {
}
private long lastTime = 0L;
private View currentView = null;
@Override
public void onClick(View view) {
long nowTime = System.currentTimeMillis();
if (nowTime - lastTime > 1000L || view.getId() == currentView.getId()) {
lastTime = nowTime;
currentView = view;
onWidgetClick(view);
}
}
/**
* startActivity
*
* @param clazz target Activity
*/
protected void go(Class<? extends Activity> clazz) {
_goActivity(clazz, null, NON_CODE, false);
}
/**
* startActivity with bundle
*
* @param clazz target Activity
*/
protected void go(Class<? extends Activity> clazz, Bundle bundle) {
_goActivity(clazz, bundle, NON_CODE, false);
}
protected void goForResult(Class<? extends Activity> clazz, int requestCode) {
_goActivity(clazz, null, requestCode, false);
}
protected void goForResult(Class<? extends Activity> clazz, Bundle bundle, int requestCode) {
_goActivity(clazz, bundle, requestCode, false);
}
/**
* Activity 跳转
*
* @param clazz 目标activity
* @param bundle 传递参数
* @param finish 是否结束当前activity
*/
private void _goActivity(Class<? extends Activity> clazz, Bundle bundle, int requestCode, boolean finish) {
if (null == clazz) {
throw new IllegalArgumentException("you must pass a target activity where to go.");
}
Intent intent = new Intent(getActivity(), clazz);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
if (null != bundle) {
intent.putExtras(bundle);
}
if (requestCode > NON_CODE) {
startActivityForResult(intent, requestCode);
} else {
startActivity(intent);
}
if (finish) {
getActivity().finish();
}
}
}
因为这里我们使用了一个伪沉浸式状态栏,所以需要在application的子节点下添加我们的APP的整体样式,这里直接贴上style
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>