public abstract class DataBindBaseActivity extends RxAppCompatActivity implements NetBroadcastReceiver.NetChangeListener {
//网络类型
private int netType;
//默认每个页面不开启网络监听,需要设置的时候,子页面,进行设置(initData initView addListener),同时重写 reload
protected boolean isStartNetListener = false;
//网络监听
private NetBroadcastReceiver netBroadcastReceiver;
public CompositeDisposable compositeDisposable;
//基础view
protected ViewGroup mRootView;
//添加view
protected LinearLayout mContentRootView;
//标题
protected TitleBar mTitleBar;
protected DataBindBaseActivity mContext;
private Unbinder mUnBinder;
//状态栏高度
protected int statusBarHeight1;
//databind
private BaseActivityBinding binding;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//防止启动页多次打开
if (!isTaskRoot()) {
Intent i = getIntent();
String action = i.getAction();
if (i.hasCategory(Intent.CATEGORY_APP_CALENDAR) && !TextUtils.isEmpty(action) && action.equals(Intent.ACTION_MAIN)) {
finish();
return;
}
}
binding = BaseActivityBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
mContext = this;
compositeDisposable = new CompositeDisposable();
//子页面 title 进行初始化
basicInitialize();
mUnBinder = ButterKnife.bind(this);
// 支持显示到刘海区域
NotchScreenManager.getInstance().setDisplayInNotch(this);
// 获取刘海屏信息
NotchScreenManager.getInstance().getNotchInfo(this, new INotchScreen.NotchScreenCallback() {
@Override
public void onResult(INotchScreen.NotchScreenInfo notchScreenInfo) {
Log.i("NotchScreenManager", "Is this screen notch? " + notchScreenInfo.hasNotch);
if (notchScreenInfo.hasNotch) {
for (Rect rect : notchScreenInfo.notchRects) {
Log.i("NotchScreenManager", "notch screen Rect = " + rect.toShortString());
// 将被遮挡的TextView下移
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) findViewById(R.id.rootView_baseActivity).getLayoutParams();
layoutParams.topMargin = rect.bottom;
findViewById(R.id.rootView_baseActivity).setLayoutParams(layoutParams);
}
}else{
setStatusBarShow(mTitleBar.getTopView());
}
}
});
//设置状态栏沉浸模式
ImmersionBar.with(this).statusBarDarkFont(true).init();
initView();
initData(savedInstanceState);
addListener();
//网络监听开启
if (isStartNetListener) {
initNetListener();
}
}
public void setStatusBarShow(View top_view) {
//这里需要手动设置一个view给状态栏
if (null != top_view) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
int statusBarHeight1 = -1;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");//获取状态栏高度
if (resourceId > 0) {
statusBarHeight1 = getResources().getDimensionPixelSize(resourceId);
}
ViewGroup.LayoutParams params = top_view.getLayoutParams();
params.height = statusBarHeight1;
params.width = ViewGroup.LayoutParams.MATCH_PARENT;
top_view.setLayoutParams(params);
}
}
}
private void basicInitialize() {
basicFindViews();
basicSetting();
}
private void basicSetting() {
addContent();
buildTitle();
}
private void addContent() {
View view = getLayout();
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams
(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
view.setLayoutParams(params);
mContentRootView.addView(view);
}
public void buildTitle() {
final TitleBar bar = mTitleBar;
if (bar == null)
return;
bar.setActivity(this);
if (!buildTitle(mTitleBar))
mTitleBar.setVisibility(View.GONE);
bar.enableLeftImageBackOnClick();
}
protected abstract View getLayout();
protected abstract boolean buildTitle(TitleBar bar);
protected abstract int getActivityBg();
private void basicFindViews() {
mRootView = findViewById(R.id.rootView_baseActivity);
mContentRootView = findViewById(R.id.content);
mTitleBar = findViewById(R.id.titleBar);
mRootView.setBackgroundResource(getActivityBg());
}
protected abstract void addListener();
protected abstract void initView();
protected abstract void initData(Bundle savedInstanceState);
@Override
protected void onDestroy() {
super.onDestroy();
if (netBroadcastReceiver != null) {
unregisterReceiver(netBroadcastReceiver);
netBroadcastReceiver=null;
}
if (mUnBinder != null) {
mUnBinder.unbind();
}
compositeDisposable.dispose();
if (EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().unregister(this);
}
//释放资源
mRootView = null;
mContentRootView = null;
mTitleBar = null;
mContext = null;
//关闭对话框
LoadingDialog.cancleProcessDialog();
}
public boolean onTouchEvent(MotionEvent event) {
if (null != this.getCurrentFocus()) {
InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
}
return super.onTouchEvent(event);
}
/**
* 点击空白区域隐藏键盘.
*/
@Override
public boolean dispatchTouchEvent(MotionEvent me) {
if (me.getAction() == MotionEvent.ACTION_DOWN) { //把操作放在用户点击的时候
View v = getCurrentFocus(); //得到当前页面的焦点,ps:有输入框的页面焦点一般会被输入框占据
if (isShouldHideKeyboard(v, me)) { //判断用户点击的是否是输入框以外的区域
hideKeyboard(v.getWindowToken()); //收起键盘
}
}
return super.dispatchTouchEvent(me);
}
/**
* 获取InputMethodManager,隐藏软键盘
*
* @param token
*/
protected void hideKeyboard(IBinder token) {
if (token != null) {
InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
}
}
/**
* 根据EditText所在坐标和用户点击的坐标相对比,来判断是否隐藏键盘,因为当用户点击EditText时则不能隐藏
*
* @param v
* @param event
* @return
*/
private boolean isShouldHideKeyboard(View v, MotionEvent event) {
if (v != null && (v instanceof EditText)) { //判断得到的焦点控件是否包含EditText
int[] l = {0, 0};
v.getLocationInWindow(l);
int left = l[0], //得到输入框在屏幕中上下左右的位置
top = l[1],
bottom = top + v.getHeight() + statusBarHeight1,
right = left + v.getWidth();
// if (event.getX() > left && event.getX() < right
// && event.getY() > top && event.getY() < bottom) {
//不判断edittext左右,只判断上下区域收起键盘
if (event.getY() > top && event.getY() < bottom) {
// 点击位置如果是EditText的区域,忽略它,不收起键盘。
return false;
} else {
return true;
}
}
// 如果焦点不是EditText则忽略
return false;
}
protected boolean stringIsEmpty(String str) {
return "".equals(str) || TextUtils.isEmpty(str);
}
protected void initNetListener() {
// Android 7.0以上需要动态注册
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// 实例化IntentFilter对象
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
netBroadcastReceiver = new NetBroadcastReceiver();
netBroadcastReceiver.setListener(this);
// 注册广播接收
registerReceiver(netBroadcastReceiver, filter);
}
findViewById(R.id.tv_reload).setOnClickListener(v -> {
if (isNetConnect()){
reLoad();
}
});
}
//网络错误重新加载
protected void reLoad() {
findViewById(R.id.content).setVisibility(View.VISIBLE);
findViewById(R.id.ll_prant_net).setVisibility(View.GONE);
}
protected void showNetError() {
findViewById(R.id.ll_prant_net).setVisibility(View.VISIBLE);
findViewById(R.id.content).setVisibility(View.GONE);
}
@Override
public void onChangeListener(int status) {
this.netType = status;
if (!isNetConnect()) {
//网络异常,请检查网络---------防止没有网络的时候
LoadingDialog.cancleProcessDialog();
showNetError();
} else {
// reLoad();
//网络恢复了
}
}
@Override
public Resources getResources() {
Resources res = super.getResources();
//解决系统改变字体大小的时候导致的界面布局混乱的问题
if (res.getConfiguration().fontScale != 1) {//非默认值
Configuration newConfig = new Configuration();
newConfig.setToDefaults();//设置默认
res.updateConfiguration(newConfig, res.getDisplayMetrics());
}
return res;
}
/**
* 判断有无网络 。
*
* @return true 有网, false 没有网络.
*/
public boolean isNetConnect() {
if (netType == DownloadManager.Request.NETWORK_MOBILE) {
return true;
} else if (netType == DownloadManager.Request.NETWORK_WIFI) {
return true;
} else if (netType == NetBroadcastReceiver.NETWORK_NONE) {
return false;
} else if (netType == 0) {
return true;
}
return false;
}
//下拉刷新相关
public void refreshFinish(SmartRefreshLayout swipeRefresh, ArrayList mList,
RecyclerView recyclerView) {
if (swipeRefresh != null) {
swipeRefresh.finishLoadMore();
swipeRefresh.finishRefresh();
}
if (mRootView.findViewById(R.id.noDataTv) != null) {
setRecycleStatus(mList,recyclerView);
}
LoadingDialog.cancleProcessDialog();
}
protected void setRecycleStatus(List
public abstract class DataBindBaseFragment extends RxFragment {
protected ViewGroup mViewGroup;
protected LinearLayout mContentRootView;
protected TitleBar mTitleBar;
protected LinearLayout rootLayout;
protected Activity mContext;
protected View mRootView;
protected boolean mIsVisible;
protected boolean mIsPrepare;
private Unbinder mUnBinder;
//databind
private BaseFragmentBinding binding;
protected boolean stringIsEmpty(String str) {
return "".equals(str) || TextUtils.isEmpty(str);
}
public void setStatusBarShow(View top_view) {
//这里需要手动设置一个view给状态栏
if (null != top_view) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
int statusBarHeight1 = -1;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");//获取状态栏高度
if (resourceId > 0) {
statusBarHeight1 = getResources().getDimensionPixelSize(resourceId);
}
ViewGroup.LayoutParams params = top_view.getLayoutParams();
params.height = statusBarHeight1;
params.width = ViewGroup.LayoutParams.MATCH_PARENT;
top_view.setLayoutParams(params);
}
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = (Activity) context;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
@Nullable
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = BaseFragmentBinding.inflate(getLayoutInflater());
mRootView = binding.getRoot();
// mRootView = inflater.inflate(R.layout.base_fragment, container, false);
rootLayout = mRootView.findViewById(R.id.rootView_baseFragment);
basicInitialize();
mUnBinder = ButterKnife.bind(this, mRootView);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
int statusBarHeight1 = -1;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
statusBarHeight1 = getResources().getDimensionPixelSize(resourceId);
}
ViewGroup.LayoutParams params = mTitleBar.getTopView().getLayoutParams();
params.height = statusBarHeight1;
params.width = ViewGroup.LayoutParams.MATCH_PARENT;
mTitleBar.getTopView().setLayoutParams(params);
}
initView(savedInstanceState);
initData(getArguments());
mIsPrepare = true;
addListener();
return mRootView;
}
private void basicInitialize() {
basicFindViews();
basicSetting();
}
private void basicSetting() {
buildTitle();
addContent();
}
private void addContent() {
mContentRootView.addView(setLayout());
}
private void buildTitle() {
final TitleBar bar = mTitleBar;
if (bar == null)
return;
bar.setActivity(mContext);
if (!buildTitle(mTitleBar))
mTitleBar.setVisibility(View.GONE);
}
protected abstract View setLayout();
protected abstract boolean buildTitle(TitleBar bar);
private void basicFindViews() {
mViewGroup = mRootView.findViewById(R.id.rootView_baseFragment);
mContentRootView = mRootView.findViewById(R.id.content_fragment);
mTitleBar = mRootView.findViewById(R.id.titleBar);
}
protected abstract void initData(Bundle arguments);
protected abstract void initView(Bundle savedInstanceState);
protected abstract void addListener();
@Override
public void onHiddenChanged(boolean isVisibleToUser) {
super.onHiddenChanged(isVisibleToUser);
this.mIsVisible = isVisibleToUser;
if (isVisibleToUser) { // 不在最前端显示 相当于调用了onPause();
return;
}else{ // 在最前端显示 相当于调用了onResume();
onLazyLoad();
}
}
protected abstract void onLazyLoad();
@Override
public void onDestroy() {
super.onDestroy();
if (EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().unregister(this);
}
if (mUnBinder != null) {
mUnBinder.unbind();
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
}
//view为gone时获取height
// public void getGoneHeight(View view){
// final int[] mHeight = {0};
// view.getViewTreeObserver().addOnGlobalLayoutListener(
// new ViewTreeObserver.OnGlobalLayoutListener(){
// @Override
// public void onGlobalLayout() {
// // gets called after layout has been done but before display
// // so we can get the height then hide the view
//
// mHeight[0] = view.getHeight();
//
// view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
// view.setVisibility(View.GONE);
//
// }
// });
// }
public void animOpen(final View view,int origHeight){
view.setVisibility(View.VISIBLE);
ValueAnimator va = createDropAnim(view,0,origHeight);
va.start();
}
public void animClose(final View view){
int origHeight = view.getHeight();
ValueAnimator va = createDropAnim(view,origHeight,0);
va.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
view.setVisibility(View.GONE);
}
});
va.start();
}
/**
* 使用动画的方式来改变高度解决visible不一闪而过出现
* @param view
* @param start 初始状态值
* @param end 结束状态值
* @return
*/
private ValueAnimator createDropAnim(final View view,int start,int end) {
ValueAnimator va = ValueAnimator.ofInt(start, end);
va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int value = (int) animation.getAnimatedValue();//根据时间因子的变化系数进行设置高度
ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
layoutParams.height = value;
view.setLayoutParams(layoutParams);//设置高度
}
});
return va;
}
//tabfragment
public class TabFragmentPagerAdapter extends FragmentPagerAdapter {
private List mlist;
public TabFragmentPagerAdapter(FragmentManager fm, List list) {
super(fm);
this.mlist = list;
}
@Override
public Fragment getItem(int arg0) {
return mlist.get(arg0);//显示第几个页面
}
@Override
public int getCount() {
return mlist.size();//有几个页面
}
}
public class TabEntity implements CustomTabEntity {
public String title;
public TabEntity(String title) {
this.title = title;
}
@Override
public String getTabTitle() {
return title;
}
@Override
public int getTabSelectedIcon() {
return 0;
}
@Override
public int getTabUnselectedIcon() {
return 0;
}
}
//下拉刷新相关
public void refreshFinish(SmartRefreshLayout swipeRefresh, ArrayList mList,
RecyclerView recyclerView) {
if (swipeRefresh != null) {
swipeRefresh.finishLoadMore();
swipeRefresh.finishRefresh();
}
if (mRootView.findViewById(R.id.noDataTv) != null) {
setRecycleStatus(mList,recyclerView);
}
LoadingDialog.cancleProcessDialog();
}
protected void setRecycleStatus(List
//base_activity.xml
//base_fragment.xml
//titlebar
public class TitleBar extends RelativeLayout {
private RelativeLayout mNaviTitleContent;
private RelativeLayout mFrameLeft;
private RelativeLayout mFrameRight;
private TextView mNaviButtonLeft;
private TextView mNaviButtonRight;
private TextView mNaviTitle;
private ImageView mMiddleImage, mLeftImage, mRightImage, mRightImageTwo;
private Activity mActivity;
private View topView, bottomView;
public TitleBar(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
public TitleBar(Context context) {
super(context);
initialize();
}
/**
*
*/
private void initialize() {
inflate();
findViews();
}
/**
*
*/
private void inflate() {
LayoutInflater.from(getContext()).inflate(R.layout.view_title_bar, this, true);
}
/**
*
*/
private void findViews() {
topView = findViewById(R.id.top_view);
mNaviTitle = findViewById(R.id.title);
mNaviTitleContent = findViewById(R.id.titleContent);
mNaviButtonLeft = findViewById(R.id.naviButtonLeft);
mNaviButtonRight = findViewById(R.id.ButtonRight);
mFrameLeft = findViewById(R.id.naviFrameLeft);
mFrameRight = findViewById(R.id.naviFrameRight);
mMiddleImage = findViewById(R.id.imageView_titleContent);
mLeftImage = findViewById(R.id.imageView_left_titlebar);
mRightImage = findViewById(R.id.imageView_right_titleBar);
mRightImageTwo = findViewById(R.id.imageView_right_titleBar_two);
bottomView = findViewById(R.id.bottom_view);
}
public void goneBottomView() {
bottomView.setVisibility(GONE);
}
public View getTopView() {
return topView;
}
public View getTitle_bar_View() {
return findViewById(R.id.view_title_bar_layout);
}
/**
* @param res
*/
public void setRightText(int res) {
mNaviButtonRight.setText(res);
}
public void setRightText(CharSequence text) {
mNaviButtonRight.setText(text);
}
//设置右侧文字颜色
public void setRightTextColor(int color) {
mNaviButtonRight.setTextColor(color);
}
/**
* @param res
*/
public void setTitleText(int res) {
mNaviTitle.setText(res);
}
public void setTitleText(SpannableString textSpan) {
mNaviTitle.setText(textSpan);
}
/**
* @param text
*/
public void setTitleText(String text) {
mNaviTitle.setText(text);
}
public void setTitleTextColor(int color) {
mNaviTitle.setTextColor(color);
}
public void setMiddleImageResource(int res) {
mMiddleImage.setImageResource(res);
}
public void setRightImageResource(int res) {
mRightImage.setImageResource(res);
}
/**
* 设置右侧图片的宽高
*
* @param w 宽 dp
* @param h 高 dp
*/
public void setRightImageResourceSize(int w, int h) {
LayoutParams layoutParams = (LayoutParams) mRightImage.getLayoutParams();
layoutParams.width = (int) (0.5f + w * Resources.getSystem().getDisplayMetrics().density);
layoutParams.height = (int) (0.5f + h * Resources.getSystem().getDisplayMetrics().density);
mRightImage.setLayoutParams(layoutParams);
}
public void setLeftImageResource(int res) {
mLeftImage.setImageResource(res);
}
/**
* 设置左侧图片的宽高
*
* @param w 宽 dp
* @param h 高 dp
*/
public void setLeftImageResourceSize(int w, int h) {
LayoutParams layoutParams = (LayoutParams) mLeftImage.getLayoutParams();
layoutParams.width = (int) (0.5f + w * Resources.getSystem().getDisplayMetrics().density);
layoutParams.height = (int) (0.5f + h * Resources.getSystem().getDisplayMetrics().density);
mLeftImage.setLayoutParams(layoutParams);
}
/**
*
*/
public void hideLeft() {
mNaviButtonLeft.setVisibility(View.INVISIBLE);
mLeftImage.setVisibility(INVISIBLE);
}
/**
*
*/
public void showTitle() {
mNaviTitle.setVisibility(View.VISIBLE);
}
/**
* @param l
*/
public void setLeftClick(OnClickListener l) {
mFrameLeft.setOnClickListener(l);
}
/**
* @param l
*/
public void setRightClick(OnClickListener l) {
mFrameRight.setOnClickListener(l);
}
/**
* @param l
*/
public void setTitleClick(OnClickListener l) {
mNaviTitle.setOnClickListener(l);
}
public void setLeftImageClick(OnClickListener l) {
mLeftImage.setOnClickListener(l);
}
public void setRightImageClick(OnClickListener l) {
mRightImage.setOnClickListener(l);
}
public void enableLeftImageBackOnClick() {
if (mFrameLeft != null)
mFrameLeft.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final Activity act = mActivity;
if (act != null)
act.finish();
}
});
}
public void setActivity(Activity act) {
this.mActivity = act;
}
}