Android

Android 比较实用的BaseActivity、BaseFr

2019-03-01  本文已影响0人  节庆007

啰嗦话不多说,先上代码!!!

BaseActivity:

/**
 * 基类
 *
 * Created by cxd on 2018/10/23
 */
public abstract class BaseActivity<P> extends AppCompatActivity {

    /**
     * presenter
     */
    public P presenter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutResId());

        // 创建presenter
        presenter = onCreatePresenter();

        // 添加类集合队列
        AppManager.getAppManager().addContext(this);
        // 注册ButterKnife
        ButterKnife.bind(this);
        // 注册EventBus
        EventBus.getDefault().register(this);
        // 设置状态栏
        setStatuBar();

        parseData();
        initView();
        initData();
        initListener();
        initReceiver();
    }

    /**
     * 广播-监听网络状态
     */
    BroadcastReceiver netReceiver =new BroadcastReceiver(){

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

                if (null != networkInfo && networkInfo.isAvailable()) {
                    int type = networkInfo.getType();
                    String lastNetState = NetChangeUtil.getInstance().getLastNetState();

                    if(!TextUtils.isEmpty(lastNetState)
                            && !TextUtils.equals(lastNetState, String.valueOf(type))
                            && (TextUtils.equals(String.valueOf(type), "0") || TextUtils.equals(String.valueOf(type), "1"))){
                        // 登录状态,而且网络切换到有网状态,通知界面刷新
                        EventBus.getDefault().post(new ReLoadEvent());
                    }

                    switch (type) {
                        case ConnectivityManager.TYPE_MOBILE: // 移动网络
                            NetChangeUtil.getInstance().setLastNetState("0");
                            break;
                        case ConnectivityManager.TYPE_WIFI: // wifi网络
                            NetChangeUtil.getInstance().setLastNetState("1");
                            break;
                    }
                } else {
                    NetChangeUtil.getInstance().setLastNetState("-1");
                }
            }
        }
    };

    /**
     * 布局文件(必须重写)
     */
    public abstract int getLayoutResId();

    /**
     * 创建presenter(需要的话重写)
     */
    public P onCreatePresenter() {
        return null;
    }

    /**
     * 解析数据
     */
    public void parseData(){}

    /**
     * 初始化视图
     */
    public void initView() {}

    /**
     * 初始化数据
     */
    public void initData() {}

    /**
     * 初始化请求
     */
    public void initRequest() {}

    /**
     * 初始化时间监听
     */
    public void initListener() {}

    /**
     * 注册网络监听的广播
     */
    private void initReceiver() {
        IntentFilter timeFilter = new IntentFilter();
        timeFilter.addAction("android.net.ethernet.ETHERNET_STATE_CHANGED");
        timeFilter.addAction("android.net.ethernet.STATE_CHANGE");
        timeFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        timeFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
        timeFilter.addAction("android.net.wifi.STATE_CHANGE");
        timeFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        registerReceiver(netReceiver, timeFilter);
    }

    /**
     * 设置状态栏(普通、沉浸、全屏)
     * 根据需要重写
     *
     * StatusBarUtil常用方法:
     *     1.设置状态栏颜色        StatusBarUtil.setColor(Activity activity, int color)
     *     2.设置状态栏半透明      StatusBarUtil.setTranslucent(Activity activity, int statusBarAlpha)
     *     3.设置状态栏全透明      StatusBarUtil.setTransparent(Activity activity)
     *     4.ImageView头部         StatusBarUtil.setTranslucentForImageView(Activity activity, int statusBarAlpha, View needOffsetView)
     *
     *
     * setSystemUiVisibility(int visibility)方法可传入的实参为:
     *     1. View.SYSTEM_UI_FLAG_VISIBLE:显示状态栏,Activity不全屏显示(恢复到有状态栏的正常情况)。
     *     2. View.INVISIBLE:隐藏状态栏,同时Activity会伸展全屏显示。
     *     3. View.SYSTEM_UI_FLAG_FULLSCREEN:Activity全屏显示,且状态栏被隐藏覆盖掉。
     *     4. View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN:Activity全屏显示,但状态栏不会被隐藏覆盖,状态栏依然可见,Activity顶端布局部分会被状态遮住。
     *     5. View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION:效果同View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
     *     6. View.SYSTEM_UI_LAYOUT_FLAGS:效果同View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
     *     7. View.SYSTEM_UI_FLAG_HIDE_NAVIGATION:隐藏虚拟按键(导航栏)。有些手机会用虚拟按键来代替物理按键。
     *     8. View.SYSTEM_UI_FLAG_LOW_PROFILE:状态栏显示处于低能显示状态(low profile模式),状态栏上一些图标显示会被隐藏。
     */
    protected void setStatuBar(){
        StatusBarUtil.setLightMode(this);
        // 鉴于上面的setLightMode自带全屏显示效果,所以在这里默认隐藏掉全屏效果,如需使用,在指定界面重写setStatuBar方法进行设置。
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }

        StatusBarUtil.setColor(this, getResources().getColor(R.color.white), 0);
    }

   /**
     * 联网恢复-重新请求最新数据
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void reLoad(ReLoadEvent event){
        initRequest();
    }

    public void startActivityWithAnim(@NonNull Intent intent) {
        super.startActivity(intent);
        overridePendingTransition(R.anim.right_to_hold, R.anim.hold_on_left);
    }

    public void finishWithAnim() {
        super.finish();
        overridePendingTransition(R.anim.left_on_hold, R.anim.hold_to_right);
    }

    @Override
    public void onBackPressed() {
        IMEUtil.closeIME(this);
        finishWithAnim();
    }

    @Override
    protected void onResume() {
        JiBuUtil.checkBuShuUpLoad();
        super.onResume();
    }

    @Override
    protected void onStop() {
        IMEUtil.closeIME(this);
        super.onStop();
    }

    @Override protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        AppManager.getAppManager().removeContext(this);
        if (null != netReceiver) {
            unregisterReceiver(netReceiver);
            netReceiver = null;
        }
        super.onDestroy();
    }
}

NetChangeUtil:

/**
 * 网络变化工具类
 *
 * Created by cxd on 2018/12/7
 */
public class NetChangeUtil {

    private static NetChangeUtil util;

    /**
     * -1  无网络
     * 0  移动网
     * 1  wifi
     */
    String lastNetState;

    public static NetChangeUtil getInstance(){
        if(null == util){
            synchronized (NetChangeUtil.class){
                if(null == util){
                    util = new NetChangeUtil();
                }
            }
        }
        return util;
    }

    public String getLastNetState() {
        return lastNetState;
    }

    public NetChangeUtil setLastNetState(String lastNetState) {
        this.lastNetState = lastNetState;
        return this;
    }
}

IMEUtil:

/**
 * 输入法控制
 *
 * Created by cxd on 2018/11/29
 */
public class IMEUtil {

    /**
     * 关闭输入法
     */
    public static void closeIME(Context context) {
        InputMethodManager manager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);

        try {
            View focusView = ((Activity) context).getCurrentFocus();
            if (manager != null && manager.isActive() && null != focusView) {
                manager.hideSoftInputFromWindow(focusView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示输入法
     */
    public static void showIME(Context context) {
        InputMethodManager manager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        manager.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.RESULT_UNCHANGED_SHOWN);
    }

    /**
     * 隐藏软键盘
     */
    public static void hideSoftKeyboard(View view) {
        ((InputMethodManager) view.getContext().getSystemService(
                Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                view.getWindowToken(), 0);
    }

    /**
     * 显示软键盘
     */
    public static void showSoftKeyboard(View view) {
        ((InputMethodManager) view.getContext().getSystemService(
                Context.INPUT_METHOD_SERVICE)).showSoftInput(
                view, InputMethodManager.SHOW_FORCED);
    }

    /**
     * 获取键盘状态
     */
    public static boolean isActiveState(Context context) {
        InputMethodManager manager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        return manager.isActive();
    }
}

整体来说比较好理解:
1.onCreatePresenter方法根据界面需求看是否需要自定义添加。
2.parseData方法解析界面传递的数据。
3.initView方法初始化视图
4.initData方法初始化数据加载
5.initRequest方法主要用于进入界面后的网络请求刷新。
6.initListener方法监听相关事件
7.网络状态监听、状态栏初始化

BaseFragment:

/**
 * 基类
 *
 * Created by cxd on 2018/11/15
 */
public abstract class BaseFragment<P> extends Fragment {

    public P presenter;

    public Activity mActivity;
    public View mContentView;

    private Unbinder unbinder;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        mActivity = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if(null == mContentView) {
            mContentView = inflater.inflate(setLayoutResourceID(), container, false);
        }
        unbinder = ButterKnife.bind(this, mContentView);
        return mContentView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // 创建presenter
        presenter = onCreatePresenter();

        parseData();
        initView();
        initData();
        initRequest();
        initListener();
    }

    /**
     * 布局文件(必须重写)
     */
    protected abstract int setLayoutResourceID();

    /**
     * 创建presenter(需要的话重写)
     */
    public P onCreatePresenter() {
        return null;
    }

    /**
     * 解析数据(仅一次)
     */
    public void parseData(){}

    /**
     * 初始化视图(可重复)
     */
    public void initView() {}

    /**
     * 初始化数据(仅一次)
     */
    public void initData() {}

    /**
     * 初始化请求(可重复)
     */
    public void initRequest() {}

    /**
     * 初始化时间监听(仅一次)
     */
    public void initListener() {}

    /**
     * 联网恢复-重新请求最新数据
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void reLoad(ReLoadEvent event){
        initRequest();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}

整体逻辑比较简单,当然了,我们可以根据自身的项目需求做进一步的扩展封装。

上一篇下一篇

猜你喜欢

热点阅读