public class Constant {

    public static final int success = 0;

    public static final String NET_ERROR = "网络出错";

    public static final int RECOMMENT = 0;//最新推荐

    public static final int WEEK = 1;//周更新

    public static final int ALLCOMMIC = 2;//所以漫画

} public class CardViewPagerFragment extends AbsBaseFragment  {

    private View mMainView;
    private Button mSideMenuOrBackBtn;

    private RhythmLayout mRhythmLayout;

    private ViewPager mViewPager;

    private CardPagerAdapter mCardPagerAdapter;

    private int mPreColor;

    private boolean mHasNext = true;

    private boolean mIsRequesting;

    private boolean isAdapterUpdated;

    private int mCurrentViewPagerPage;

    private ViewSelectorLayout mViewSelectorLayout;
    private List<Card> mCardList;

//    private ProgressHUD mProgressHUD;


    private RhythmAdapter mRhythmAdapter;

    private static CardViewPagerFragment mFragment;


    private IRhythmItemListener rhythmItemListener = new IRhythmItemListener() {
        public void onRhythmItemChanged(int paramInt) {
        }

        public void onSelected(final int paramInt) {
            CardViewPagerFragment.this.mHandler.postDelayed(new Runnable() {
                public void run() {
                    mViewPager.setCurrentItem(paramInt);
                }
            }, 100L);
        }

        public void onStartSwipe() {
        }
    };

    private ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        public void onPageScrollStateChanged(int paramInt) {
        }

        public void onPageScrolled(int paramInt1, float paramFloat, int paramInt2) {

        }

        public void onPageSelected(int position) {
            onAppPagerChange(position);
//            if (mHasNext && (position > -10 + mCardList.size()) && !mIsRequesting) {
////                fetchData();
//            }
        }
    };

    public static CardViewPagerFragment getInstance() {
        if (mFragment == null) {
            mFragment = new CardViewPagerFragment();
        }
        return mFragment;
    }


    @Override
    protected View initViews(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.fragment_niceapp, null);

        mViewSelectorLayout = new ViewSelectorLayout(getActivity(),view);

        mMainView = view.findViewById(R.id.main_view);

        mRhythmLayout = (RhythmLayout) view.findViewById(R.id.box_rhythm);
        mViewPager = (ViewPager) view.findViewById(R.id.pager);

        setViewPagerScrollSpeed(mViewPager, 400);
        mRhythmLayout.setScrollRhythmStartDelayTime(400);
        int height = (int) mRhythmLayout.getRhythmItemWidth() + (int) TypedValue.applyDimension(1, 10.0F, getResources().getDisplayMetrics());
        mRhythmLayout.getLayoutParams().height = height;
//        ((RelativeLayout.LayoutParams) mPullToRefreshViewPager.getLayoutParams()).bottomMargin = height;
        ((RelativeLayout.LayoutParams)  mViewPager.getLayoutParams()).bottomMargin = height;
        return mViewSelectorLayout;
    }


    @Override
    protected void initActions(View paramView) {
        mRhythmLayout.setRhythmListener(rhythmItemListener);
        mViewPager.setOnPageChangeListener(onPageChangeListener);
    }

    @Override
    protected void initData() {
        mCardList = new ArrayList<>();
    }


    private void setViewPagerScrollSpeed(ViewPager viewPager, int speed) {
        try {
            Field field = ViewPager.class.getDeclaredField("mScroller");
            field.setAccessible(true);
            ViewPagerScroller viewPagerScroller = new ViewPagerScroller(viewPager.getContext(), new OvershootInterpolator(0.6F));
            field.set(viewPager, viewPagerScroller);
            viewPagerScroller.setDuration(speed);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }


    private void onAppPagerChange(int position) {
        mRhythmLayout.showRhythmAtPosition(position);
        Card post = this.mCardList.get(position);
        int currColor = HexUtils.getHexColor(post.getBackgroundColor());
        AnimatorUtils.showBackgroundColorAnimation(this.mMainView, mPreColor, currColor, 400);
        mPreColor = currColor;

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewSelectorLayout.show_LoadingView();
        fetchData();

    }


    private void fetchData() {
        AppDao.getInstance().subscribeByUser("0", new CallbackListener<AllBookModels>() {
            @Override
            public void onStringResult(String result) {
                super.onStringResult(result);
                Log.i("scirbe", "result---->" + result);
            }

            @Override
            public void onSuccess(AllBookModels result) {
                super.onSuccess(result);
                mViewSelectorLayout.show_ContentView();
                handData(result.Return.List);
            }

            @Override
            public void onError(Exception e) {
                super.onError(e);
            }
        });

//        ArrayList<Card> cardList = new ArrayList<>();
//        for (int i = 0; i < 10; i++) {
//            int m = i % 10;
//            Card card = addData(m);
//            cardList.add(card);
//        }
//        mPreColor = HexUtils.getHexColor(cardList.get(0).getBackgroundColor());

    }

    private void handData(ArrayList<AllBookModels.ReturnClazz.AllBook> list) {
        ArrayList<Card> cardList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Card card = new Card();
            card.setId(list.get(i).Id);
            card.setTitle(list.get(i).Title);
            if(list.get(i).LastChapter != null)
            card.setSubTitle(list.get(i).LastChapter.Title);
            card.setDigest(list.get(i).Explain);
            card.setAuthorName(list.get(i).Author);
            if(list.get(i).LastChapter != null)
            card.setUpNum(Integer.valueOf(list.get(i).LastChapter.ChapterNo));
            card.setBackgroundColor("#795548");
            card.setCoverImgerUrl(list.get(i).FrontCover);
            card.setIconUrl(list.get(i).FrontCover);
            cardList.add(card);
        }

        updateAppAdapter(cardList);
        onAppPagerChange(0);
    }


    private void updateAppAdapter(List<Card> cardList) {
        if ((getActivity() == null) || (getActivity().isFinishing())) {
            return;
        }

        if (cardList.isEmpty()) {
            this.mMainView.setBackgroundColor(this.mPreColor);
            return;
        }
        int size = mCardList.size();

        if (mCardPagerAdapter == null) {
            mCurrentViewPagerPage = 0;
            mCardPagerAdapter = new CardPagerAdapter(getActivity().getSupportFragmentManager(), cardList);
            mViewPager.setAdapter(mCardPagerAdapter);
        } else {
            mCardPagerAdapter.addCardList(cardList);
            mCardPagerAdapter.notifyDataSetChanged();
        }
        addCardIconsToDock(cardList);

        this.mCardList = mCardPagerAdapter.getCardList();

        if (mViewPager.getCurrentItem() == size - 1)
            mViewPager.setCurrentItem(1 + mViewPager.getCurrentItem(), true);
    }

    private void addCardIconsToDock(final List<Card> cardList) {
        if (mRhythmAdapter == null) {
            resetRhythmLayout(cardList);
            return;
        }
        mRhythmAdapter.addCardList(cardList);
        mRhythmAdapter.notifyDataSetChanged();
    }

    private void resetRhythmLayout(List<Card> cardList) {
        if (getActivity() == null)
            return;
        if (cardList == null)
            cardList = new ArrayList<>();
        mRhythmAdapter = new RhythmAdapter(getActivity(), mRhythmLayout, cardList);
        mRhythmLayout.setAdapter(mRhythmAdapter);
    }



} public class CategoryFragment extends Fragment {
    @Bind(R.id.viewpager_catorage)
    ViewPager mViewPager;
    @Bind(R.id.viewpager_book)
    ViewPager mViewPager_book;
    @Bind(R.id.indicator_default)
    CircleIndicator mCircleIndicator;
    @Bind(R.id.tabs)
    TabLayout mTabLayout;
    @Bind(R.id.refreshlayout)
    MaterialRefreshLayout mMaterialRefreshLayout;
    ViewSelectorLayout mViewSelectorLayout;

    private PlayViewHandler mViewHandler = new PlayViewHandler();



//    private

   public static CategoryFragment newInstance() {
        CategoryFragment fragment = new CategoryFragment();
        return fragment;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setupViewPager(mViewPager_book);
        mViewSelectorLayout.show_LoadingView();
        getAvdData();

        mViewPager_book.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener()
        {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                switch (position)
                {
                    case 0:
                        updateHeight(oldHeith1);
                        break;
                    case 1:
                        updateHeight(oldHeith2);
                        break;
                    case 2:
                        updateHeight(oldHeith3);
                        break;
                }
            }
        });
    }



    private void getAvdData() {
        AppDao.getInstance().getSlideData(new CallbackListener<AdvModel>() {


            @Override
            public void onSuccess(AdvModel result) {
                super.onSuccess(result);
                if (result != null) {
                    final ViewPagerAdvAdapter mAdapter = new ViewPagerAdvAdapter(getActivity(), result.list);
                    mViewPager.setAdapter(mAdapter);
                    mCircleIndicator.setViewPager(mViewPager);
                    mViewHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mViewHandler.slidingPlayView(mViewPager, mAdapter.getCount());
                        }
                    }, 6_000);
                    mViewSelectorLayout.show_ContentView();
                }


            }
        });
    }

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

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_category,null);
        mViewSelectorLayout = new ViewSelectorLayout(getActivity(),v);
        ButterKnife.bind(this, v);
        return mViewSelectorLayout;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mMaterialRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
                materialRefreshLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mMaterialRefreshLayout.finishRefresh();
                    }
                }, 1_000);
            }

            @Override
            public void onfinish() {
                super.onfinish();
            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                super.onRefreshLoadMore(materialRefreshLayout);
                handRefreshMore(materialRefreshLayout);
            }

        });

    }

    private void handRefreshMore(MaterialRefreshLayout materialRefreshLayout) {
        switch (mViewPager_book.getCurrentItem())
        {
            case 0:
                EventBus.getDefault().post(new RefreshEvent(materialRefreshLayout,"refresh_hot"));
                break;
            case 1:
                EventBus.getDefault().post(new RefreshEvent(materialRefreshLayout,"refresh_same"));
                break;
            case 2:
                EventBus.getDefault().post(new RefreshEvent(materialRefreshLayout,"refresh_mouse"));
                break;
            case 3:

                break;
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);
    }

    private void setupViewPager(ViewPager viewPager) {
        BookPagerAdapter adapter = new BookPagerAdapter(getChildFragmentManager());
        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(2);
        mTabLayout.setupWithViewPager(viewPager);
        mTabLayout.setSelectedTabIndicatorColor(Color.parseColor("#ffffff"));
        mTabLayout.setTabTextColors(Color.parseColor("#dfdfdf"), Color.parseColor("#ffffff"));
    }

    private int oldHeith1,oldHeith2,oldHeith3;

    public void onEvent(Object event)
    {
        if(event instanceof ViewPagerHeightEvent)
        {
            ViewPagerHeightEvent hightEvent = (ViewPagerHeightEvent) event;
            int curH = hightEvent.heith;
            if(hightEvent.heith<=0){return;}

            if(hightEvent.vp.equals("hot")&&mViewPager_book.getCurrentItem()==0&&oldHeith1!=curH)
            {
                updateHeight(curH);
                oldHeith1 = curH;
            }else if(hightEvent.vp.equals("same")&&mViewPager_book.getCurrentItem()==1&&oldHeith2!=curH)
            {
                updateHeight(curH);
                oldHeith2 = curH;
            }else if(hightEvent.vp.equals("mouse")&&mViewPager_book.getCurrentItem()==2&&oldHeith3!=curH)
            {
                updateHeight(curH);
                oldHeith3 = curH;
            }

        }else
        {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if(mMaterialRefreshLayout!= null)
                    {
                        mMaterialRefreshLayout.finishRefresh();
                        mMaterialRefreshLayout.finishRefreshLoadMore();
                    }
                }
            },1000);
        }


    }
    public void updateHeight(int heith)
    {
        ViewGroup.LayoutParams layoutParams =  mViewPager_book.getLayoutParams();
        layoutParams.height = heith;
        mViewPager_book.requestLayout();
    }

} public class HomeFragment extends Fragment implements ReLoadCallbackListener {
    @Bind(R.id.recycler_view) RecyclerView recyclerView;
    @Bind(R.id.refreshlayout) MaterialRefreshLayout refreshLayout;
    private HomeRecyclerViewAdapter mAdapter;
    private ArrayList<AllBookModels.ReturnClazz.AllBook> mDataSet;
    private ViewSelectorLayout viewSelectorLayout;

    public static HomeFragment newInstance() {
        HomeFragment fragment = new HomeFragment();
        return fragment;
    }

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

    @Override
    public void onResume() {
        super.onResume();
        if(null!=mAdapter)
        {
            mAdapter.updateData(mDataSet);
        }

        if(refreshLayout!=null)
        {
            refreshLayout.finishRefresh();
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_home,null);
        ButterKnife.bind(this,v);
        viewSelectorLayout = new ViewSelectorLayout(getActivity(),v);
        viewSelectorLayout.setReLoadCallbackListener(this);
        return viewSelectorLayout;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // Layout Managers:
        final StaggeredGridLayoutManager layoutManager =
                new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);

        // Item Decorator:
//        recyclerView.addItemDecoration(new DividerItemDecoration(getResources().getDrawable(R.drawable.divider)));
//        recyclerView.setItemAnimator(new FadeInLeftAnimator());

//        /* Listeners */
//        recyclerView.setOnScrollListener(onScrollListener);
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewSelectorLayout.show_LoadingView();
        getBookData();

        refreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
                getBookData();
            }
        });
    }

    public void getBookData()
    {
        AppDao.getInstance().getAllBook(new CallbackListener<AllBookModels>() {
            @Override
            public void onStringResult(String result) {
                super.onStringResult(result);
                Log.i("cjj", "res----->" + result);
            }

            @Override
            public void onSuccess(AllBookModels result) {
                super.onSuccess(result);
                mDataSet =  (ArrayList) result.Return.List;
                if (mAdapter == null) {


                    mAdapter = new HomeRecyclerViewAdapter(getActivity(),mDataSet);
                    recyclerView.setAdapter(mAdapter);



                } else {
                    mAdapter.updateData(mDataSet);
                }

                viewSelectorLayout.show_ContentView();
                refreshLayout.finishRefresh();
            }

            @Override
            public void onError(Exception e) {
                super.onError(e);
//                toastMsg(Constant.NET_ERROR);
                toastMsg(e+"");
                viewSelectorLayout.show_FailView();
                refreshLayout.finishRefresh();
            }
        });
    }

    private void toastMsg(String msg) {
        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
    }

    public void onEvent(UpdateHomeDataEvent event)
    {

    }



    @Override
    public void onDestroyView() {
        super.onDestroyView();




        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);
    }

    /**
     * Substitute for our onScrollListener for RecyclerView
     */
    RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            Log.e("ListView", "onScrollStateChanged");
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            // Could hide open views here if you wanted. //
        }
    };


    @Override
    public void onReLoadCallback() {
        viewSelectorLayout.show_LoadingView();
        getBookData();
    }
} public class SubscribeFragment extends Fragment {

    public static SubscribeFragment newInstance() {
        SubscribeFragment fragment = new SubscribeFragment();
        return fragment;
    }

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

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

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

} public class ScreenUtil {
    public static final Context context = MosuePaintAppication.appication;

    private ScreenUtil()
    {
        throw new UnsupportedOperationException("禁止实例化该类！");
    }

    /**
     * 获得屏幕高度
     * @param context
     * @return
     */
    public static int getScreenWidth()
    {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    /**
     * 获得屏幕宽度
     * @param context
     * @return
     */
    public static int getScreenHeight()
    {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

    /**
     * 获得状态栏的高度
     * @param context
     * @return
     */
    public static int getStatusHeight()
    {
        int statusHeight = -1;
        try
        {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height").get(object).toString());
            statusHeight = context.getResources().getDimensionPixelSize(height);
        } catch (Exception e){
            e.printStackTrace();
        }
        return statusHeight;
    }

    /**
     * 获取当前屏幕截图，包含状态栏
     * @param activity
     * @return
     */
    public static Bitmap snapShotWithStatusBar(Activity activity)
    {
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bmp = view.getDrawingCache();
        int width = getScreenWidth();
        int height = getScreenHeight();
        Bitmap bp = null;
        bp = Bitmap.createBitmap(bmp, 0, 0, width, height);
        view.destroyDrawingCache();
        return bp;

    }

    /**
     * 获取当前屏幕截图，不包含状态栏
     * @param activity
     * @return
     */
    public static Bitmap snapShotWithoutStatusBar(Activity activity)
    {
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bmp = view.getDrawingCache();
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;

        int width = getScreenWidth();
        int height = getScreenHeight();
        Bitmap bp = null;
        bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height - statusBarHeight);
        view.destroyDrawingCache();
        return bp;

    }

    /**
     * 获取屏幕尺寸与密度.
     *
     * @param context the context
     * @return mDisplayMetrics
     */
    public static DisplayMetrics getDisplayMetrics(Context context) {
        Resources mResources;
        if (context == null) {
            mResources = Resources.getSystem();

        } else {
            mResources = context.getResources();
        }
        //DisplayMetrics{density=1.5, width=480, height=854, scaledDensity=1.5, xdpi=160.421, ydpi=159.497}
        //DisplayMetrics{density=2.0, width=720, height=1280, scaledDensity=2.0, xdpi=160.42105, ydpi=160.15764}
        DisplayMetrics mDisplayMetrics = mResources.getDisplayMetrics();
        return mDisplayMetrics;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


} public class StatusBarCompat
{
    private static final int INVALID_VAL = -1;
    private static final int COLOR_DEFAULT = Color.parseColor("#20000000");

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public static void compat(Activity activity, int statusColor)
    {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        {
//            if (statusColor != INVALID_VAL)
//            {
//                activity.getWindow().setStatusBarColor(statusColor);
//            }
            return;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
        {
            int color = COLOR_DEFAULT;
            ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content);
            if (statusColor != INVALID_VAL)
            {
                color = statusColor;
            }
            View statusBarView = contentView.getChildAt(0);
            //改变颜色时避免重复添加statusBarView
            if (statusBarView != null && statusBarView.getMeasuredHeight() == getStatusBarHeight(activity))
            {
                statusBarView.setBackgroundColor(color);
                return;
            }
            statusBarView = new View(activity);
            ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    getStatusBarHeight(activity));
            statusBarView.setBackgroundColor(color);
            contentView.addView(statusBarView, lp);
        }

    }

    public static void compat(Activity activity)
    {
        compat(activity, INVALID_VAL);
    }


    public static int getStatusBarHeight(Context context)
    {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0)
        {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }
} public class VersionUtil {

    public static boolean checkVersionIntMoreThan14()
    {
        if (android.os.Build.VERSION.SDK_INT >= 14) {
            return true;
        }
        return false;
    }

    public static boolean checkVersionIntMoreThan17()
    {
        if (android.os.Build.VERSION.SDK_INT >= 17) {
            return true;
        }
        return false;
    }

    public static boolean checkVersionIntMoreThan19()
    {
        if (android.os.Build.VERSION.SDK_INT > 19) {
            return true;
        }
        return false;
    }

} public class BlurEffect implements Effect {

    private float Value;


    private BlurAsyncTask mBlurAsyncTask;

    public BlurEffect(float value) {
        Value = value;
    }

    public void setValue(float value) {
        Value = value;
    }

    @Override
    public float getValue() {
        return Value;
    }

    @Override
    public void effect(ViewGroup vp, ImageView view) {

        if(mBlurAsyncTask!= null){
            mBlurAsyncTask.cancel(true);
        }

        mBlurAsyncTask= new BlurAsyncTask(vp, view, Blur.convertFromView(vp));
        mBlurAsyncTask.execute((int) Value);
    }


    /**
     * Async task used to process blur out of ui thread
     */
    private class BlurAsyncTask extends AsyncTask<Integer, Void, Bitmap> {

        private View mViewGroup;
        private ImageView mImageView;

        private Bitmap mOriginalBitmap;

        private Context mContext;

//        private long starTime;


        public BlurAsyncTask(View viewGroup, ImageView imageView, Bitmap originalBitmap) {
            mOriginalBitmap = originalBitmap;
            mViewGroup = viewGroup;
            mImageView = imageView;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mContext = mViewGroup.getContext();
            mImageView.setImageBitmap(null);
//            starTime=System.currentTimeMillis();
//
        }

        @Override
        protected Bitmap doInBackground(Integer... params) {
            //process to the blue
            if (!isCancelled() && mOriginalBitmap != null) {

//                Bitmap b
//                        =Bitmap.createScaledBitmap(mOriginalBitmap, mOriginalBitmap.getWidth() / 4,
//                        mOriginalBitmap.getHeight() / 4, false);
//
//                if (b == null) {
//                    b = mOriginalBitmap;
//                }
                Bitmap bm = Blur.fastblur(mContext, mOriginalBitmap, params[0]);
                mOriginalBitmap.recycle();
                mOriginalBitmap = null;
                return bm;
            } else {
                return null;
            }


        }

        @Override
        @SuppressLint("NewApi")
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            if (bitmap != null) {
                mImageView.setImageBitmap(bitmap);
            }

//            Log.e("tag",System.currentTimeMillis()-starTime+"ms");
            mViewGroup.destroyDrawingCache();
            mViewGroup.setDrawingCacheEnabled(false);
            mViewGroup = null;
            mImageView = null;
            mContext = null;
        }


    }

} public abstract class Delegate implements View.OnClickListener {


    protected SweetSheet.Status mStatus = SweetSheet.Status.DISMISS;

    protected ViewGroup mParentVG;
    protected View mRootView;
    private ImageView mBg;
    private Effect mEffect;
    private boolean mIsBgClickEnable=true;

    protected SweetSheet.OnMenuItemClickListener mOnMenuItemClickListener;

    protected void init(ViewGroup parentVG) {
        mParentVG = parentVG;
        mBg = new ImageView(parentVG.getContext());
        mRootView = createView();
        mBg.setOnClickListener(this);
    }

    /**
     * 生成视图
     * @return
     */
    protected abstract View createView();

    /**
     * 设置数据源
     * @param list
     */
    protected abstract void setMenuList(List<MenuEntity> list);

    protected void toggle() {

        switch (mStatus) {

            case SHOW:
            case SHOWING:
                dismiss();
                break;

            case DISMISS:
            case DISMISSING:
                show();
                break;

            default:
                break;
        }
    }

    protected void show() {

        if (getStatus() != SweetSheet.Status.DISMISS) {
            return;
        }
        mBg.setClickable(mIsBgClickEnable);
        mBg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bgListener != null) {
                    bgListener.onClick();
                }
            }
        });
        showShowdown();

    }


    /**
     * 显示模糊背景
     */
    protected void showShowdown() {

        ViewHelper.setTranslationY(mRootView, 0);
        mEffect.effect(mParentVG,mBg);
        ViewGroup.LayoutParams lp =
                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

        if(mBg.getParent()!= null){
            mParentVG.removeView(mBg);
        }

        mParentVG.addView(mBg, lp);
        ViewHelper.setAlpha(mBg, 0);
        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mBg, "alpha", 0, 1);
        objectAnimator.setDuration(400);
        objectAnimator.start();
    }

    /**
     * 隐藏模糊背景
     */
    protected void dismissShowdown() {

        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mBg, "alpha", 1, 0);
        objectAnimator.setDuration(400);
        objectAnimator.start();
        objectAnimator.addListener(new SimpleAnimationListener() {

            @Override
            public void onAnimationEnd(Animator animation) {

                mParentVG.removeView(mBg);
            }


        });
    }

    /**
     * 消失
     */
    protected void dismiss() {
        if (getStatus() == SweetSheet.Status.DISMISS){
            return;
        }
        mBg.setClickable(false);
        dismissShowdown();

        ObjectAnimator translationOut = ObjectAnimator.ofFloat(mRootView,
                "translationY", 0, mRootView.getHeight());
        translationOut.setDuration(600);
        translationOut.setInterpolator(new DecelerateInterpolator());
        translationOut.addListener(new SimpleAnimationListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                mStatus =
                        SweetSheet.Status.DISMISSING;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                mStatus = SweetSheet.Status.DISMISS;
                mParentVG.removeView(mRootView);
            }

        });
        translationOut.start();


    }


    protected void setBackgroundEffect(Effect effect) {
        mEffect=effect;

    }

    protected void setOnMenuItemClickListener(SweetSheet.OnMenuItemClickListener onItemClickListener) {
        mOnMenuItemClickListener = onItemClickListener;
    }


    public BgListener bgListener;

    public void setBgListener(BgListener bgListener)
    {
        this.bgListener = bgListener;
    }

    public interface BgListener
    {
        public void onClick();
    }

    /**
     * 延时消失
     */
    protected void delayedDismiss() {


        mParentVG.postDelayed(new Runnable() {
            @Override
            public void run() {
                dismiss();
            }
        }, 300);
    }

    protected SweetSheet.Status getStatus() {
        return mStatus;
    }

    @Override
    public void onClick(View v) {
        dismiss();


    }

    public void setBackgroundClickEnable(boolean isBgClickEnable){
        mIsBgClickEnable=isBgClickEnable;
    }
} public class RecyclerViewDelegate extends Delegate  {

    private SweetView mSweetView;
    private RecyclerView mRV;
    private MenuRVAdapter mMenuRVAdapter;
    private CRImageView sliderIm;
    private FreeGrowUpParentRelativeLayout mFreeGrowUpParentRelativeLayout;
    private boolean mIsDragEnable;
    private int mContentViewHeight;

    public RecyclerViewDelegate(boolean dragEnable) {
        mIsDragEnable=dragEnable;

    }

    public RecyclerViewDelegate(boolean dragEnable  ,int contentViewHeight) {
        mContentViewHeight = contentViewHeight;
        mIsDragEnable = dragEnable;
    }

    @Override
    protected View createView() {

        View rootView = LayoutInflater.from(mParentVG.getContext())
                .inflate(R.layout.layout_rv_sweet, null, false);

        mSweetView = (SweetView) rootView.findViewById(R.id.sv);
        mFreeGrowUpParentRelativeLayout = (FreeGrowUpParentRelativeLayout) rootView.findViewById(R.id.freeGrowUpParentF);
        mRV = (RecyclerView) rootView.findViewById(R.id.rv);
        sliderIm = (CRImageView) rootView.findViewById(R.id.sliderIM);
        mRV.setLayoutManager(new LinearLayoutManager(mParentVG.getContext(), LinearLayoutManager.VERTICAL, false));
        mSweetView.setAnimationListener(new AnimationImp());
        if(mContentViewHeight > 0){
            mFreeGrowUpParentRelativeLayout.setContentHeight(mContentViewHeight);
        }

        return rootView;
    }

    public  RecyclerViewDelegate setContentHeight(int height){

        if(height >0 && mFreeGrowUpParentRelativeLayout != null){
            mFreeGrowUpParentRelativeLayout.setContentHeight(height);
        }else{
            mContentViewHeight=height;
        }

        return this;

    }



    protected void setMenuList(final List<MenuEntity> menuEntities) {

        mMenuRVAdapter = new MenuRVAdapter(menuEntities, SweetSheet.Type.RecyclerView);
        mRV.setAdapter(mMenuRVAdapter);
        mMenuRVAdapter.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (mOnMenuItemClickListener != null) {
                    if (mOnMenuItemClickListener.onItemClick(position, menuEntities.get(position))) {
                        delayedDismiss();
                    }
                }
            }
        });
        mRV.setLayoutAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                mRV.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        return true;
                    }
                });
                mFreeGrowUpParentRelativeLayout.setClipChildren(false);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mRV.setOnTouchListener(null);

                mFreeGrowUpParentRelativeLayout.setClipChildren(true);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

    }

    protected void show() {
        super.show();
        ViewGroup.LayoutParams lp =
                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);


        if(mRootView.getParent()!= null){
            mParentVG.removeView(mRootView);
        }

        mParentVG.addView(mRootView, lp);
        mSweetView.show();
    }

    @Override
    protected void dismiss() {
        super.dismiss();

    }


    class AnimationImp implements SweetView.AnimationListener {

        @Override
        public void onStart() {
            mFreeGrowUpParentRelativeLayout.reset();
            mStatus = SweetSheet.Status.SHOWING;
            sliderIm.setVisibility(View.INVISIBLE);
            mRV.setVisibility(View.GONE);
        }

        @Override
        public void onEnd() {


            if(  mStatus==SweetSheet.Status.SHOWING) {

                mStatus = SweetSheet.Status.SHOW;

                if(mIsDragEnable) {
                    sliderIm.setVisibility(View.VISIBLE);
                    sliderIm.circularReveal(sliderIm.getWidth() / 2, sliderIm.getHeight() / 2, 0, sliderIm.getWidth());
                }
            }

        }

        @Override
        public void onContentShow() {
            mRV.setVisibility(View.VISIBLE);
            mRV.setAdapter(mMenuRVAdapter);
            mRV.scheduleLayoutAnimation();
        }
    }
} public class SweetSheet {

    public static final String Tag="SweetSheet";
    public enum Type{
        RecyclerView,Viewpager,Custom
    }


    private ViewGroup mParentVG;
    private Delegate mDelegate;
    private Effect mEffect=new NoneEffect();
    private OnMenuItemClickListener mOnMenuItemClickListener;
    private boolean mIsBgClickEnable=true;


    public SweetSheet(RelativeLayout parentVG) {
        mParentVG = parentVG;
    }

    public SweetSheet(FrameLayout parentVG) {
        mParentVG = parentVG;
    }



    public SweetSheet(ViewGroup parentVG) {

        if (parentVG instanceof FrameLayout || parentVG instanceof RelativeLayout) {

        } else {
            throw new IllegalStateException("ViewGroup  must FrameLayout or  RelativeLayout.");
        }
        mParentVG = parentVG;

    }


    public void setDelegate(Delegate delegate){
        mDelegate=delegate;
        mDelegate.init(mParentVG);
        setup();

    }


    private void setup() {

        if(mOnMenuItemClickListener != null){
            mDelegate.setOnMenuItemClickListener(mOnMenuItemClickListener);
        }
        if(mMenuEntities != null){
            mDelegate.setMenuList(mMenuEntities);
        }
        mDelegate.setBackgroundEffect(mEffect);
        mDelegate.setBackgroundClickEnable(mIsBgClickEnable);
    }


    public void setBackgroundClickEnable(boolean isBgClickEnable){
        if(mDelegate != null){
            mDelegate.setBackgroundClickEnable(isBgClickEnable);
        }else{
            mIsBgClickEnable=isBgClickEnable;
        }
    }


    public void setBackgroundEffect(Effect effect) {

        if(mDelegate != null) {
            mDelegate.setBackgroundEffect(effect);
        }else{
            mEffect=effect;
        }
    }


    public void setOnMenuItemClickListener(OnMenuItemClickListener onItemClickListener) {
        if(mDelegate != null) {
            mDelegate.setOnMenuItemClickListener(onItemClickListener);
        }else{
            mOnMenuItemClickListener=onItemClickListener;
        }
    }

    public void setBgListener(Delegate.BgListener listener)
    {
        mDelegate.setBgListener(listener);
    }

    public void show() {

        if(mDelegate != null) {

            mDelegate.show();
        }else{
            Log.e(Tag,"you must setDelegate before");
        }
    }

    public void dismiss() {
        if(mDelegate != null) {

            mDelegate.dismiss();
        }else{
            Log.e(Tag,"you must setDelegate before");
        }

    }

    public void toggle() {
        if(mDelegate != null) {

            mDelegate.toggle();
        }else{
            Log.e(Tag,"you must setDelegate before");
        }

    }

    public boolean isShow() {

        if(mDelegate == null) {

           return  false;
        }
        if (mDelegate.getStatus() == Status.SHOW || mDelegate.getStatus() == Status.SHOWING) {
            return true;
        }
        return false;
    }
    private List<MenuEntity> mMenuEntities;

    public void setMenuList(List<MenuEntity> menuEntities) {
        if(mDelegate != null) {

            mDelegate.setMenuList(menuEntities);
        }else{
            mMenuEntities=menuEntities;
        }

    }

    public void setMenuList(@MenuRes int menuRes) {

        Menu menu = new PopupMenu(mParentVG.getContext(), null).getMenu();
        new MenuInflater(mParentVG.getContext()).inflate(menuRes, menu);
        List<MenuEntity> menuEntities = getMenuEntityFormMenuRes(menu);

        if(mDelegate != null) {

            mDelegate.setMenuList(menuEntities);
        }else{
            mMenuEntities=menuEntities;
        }

    }


    /**
     * 当前只处理一级的菜单
     *
     * @param menu
     * @return
     */
    private List<MenuEntity> getMenuEntityFormMenuRes(Menu menu) {

        List<MenuEntity> list = new ArrayList<>();
        for (int i = 0; i < menu.size(); i++) {
            MenuItem item = menu.getItem(i);

            if (item.isVisible()) {
                MenuEntity itemEntity = new MenuEntity();
                itemEntity.title = item.getTitle().toString();
                itemEntity.icon = item.getIcon();
                list.add(itemEntity);
            }
        }
        return list;
    }

    protected enum Status {

        SHOW, SHOWING,
        DISMISS, DISMISSING
    }

    public interface OnMenuItemClickListener {
        boolean onItemClick(int position, MenuEntity menuEntity);
    }

} public class ArcAnimator extends Animator {

    public static ArcAnimator createArcAnimator(View clipView, View nestView,
                                                float degree, Side side){

        return createArcAnimator(clipView, Utils.centerX(nestView), Utils.centerY(nestView),
                degree, side);
    }

    public static ArcAnimator createArcAnimator(View clipView, float endX, float endY,
                                                float degree, Side side){

        ArcMetric arcMetric = ArcMetric.evaluate(Utils.centerX(clipView), Utils.centerY(clipView),
                endX, endY, degree, side);
        return new ArcAnimator(arcMetric, clipView);
    }

    ArcMetric mArcMetric;
    WeakReference<View> mTarget;
    WeakReference<ObjectAnimator> mAnimator;
    float mValue;


    private ArcAnimator(ArcMetric arcmetric, View target) {
        mArcMetric = arcmetric;
        mTarget = new WeakReference<>(target);

        mAnimator = new WeakReference<>(
                ObjectAnimator.ofFloat(
                        ArcAnimator.this, // target
                        "degree", // property
                        arcmetric.getStartDegree(),
                        arcmetric.getEndDegree())
        );
    }

    void setDegree(float degree){
        mValue = degree;
        View clipView = mTarget.get();
        float x = mArcMetric.getAxisPoint().x + mArcMetric.mRadius
                * Utils.cos(degree);
        float y = mArcMetric.getAxisPoint().y - mArcMetric.mRadius
                * Utils.sin(degree);
        ViewHelper.setX(clipView,x - clipView.getWidth() / 2);
        ViewHelper.setY(clipView,y - clipView.getHeight() / 2);
    }

    float getDegree(){
        return mValue;
    }

    @Override
    public long getStartDelay() {
        Animator a = mAnimator.get();
        return a == null ? 0 : a.getDuration();
    }

    @Override
    public void setStartDelay(long startDelay) {
        Animator a = mAnimator.get();
        if(a != null) a.setStartDelay(startDelay);
    }

    @Override
    public ArcAnimator setDuration(long duration) {
        Animator a = mAnimator.get();
        if(a != null) a.setDuration(duration);
        return this;
    }

    @Override
    public long getDuration() {
        Animator a = mAnimator.get();
        return a == null ? 0 : a.getDuration();
    }

    @Override
    public void setInterpolator(Interpolator value) {
        Animator a = mAnimator.get();
        if(a != null) a.setInterpolator(value);
    }

    @Override
    public void start() {
        super.start();
        Animator a = mAnimator.get();
        if(a != null) a.start();
    }

    @Override
    public void end() {
        super.end();
        Animator a = mAnimator.get();
        if(a != null) a.end();
    }

    @Override
    public void cancel() {
        super.cancel();
        Animator a = mAnimator.get();
        if(a != null) a.cancel();
    }

    @Override
    public void addListener(AnimatorListener listener) {
        Animator a = mAnimator.get();
        if(a != null) a.addListener(listener);
    }

    @Override
    public void setupEndValues() {
        super.setupEndValues();
        Animator a = mAnimator.get();
        if(a != null) a.setupEndValues();
    }

    @Override
    public void setupStartValues() {
        super.setupStartValues();
        Animator a = mAnimator.get();
        if(a != null) a.setupStartValues();
    }

    @Override
    public boolean isRunning() {
        Animator a = mAnimator.get();
        return a != null && a.isRunning();
    }

    @Override
    public String toString() {
        return mArcMetric.toString();
    }
}
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;
import com.cjj.mousepaint.constants.Constant;
import com.cjj.mousepaint.fragment.CardViewPagerFragment;
import com.cjj.mousepaint.fragment.CategoryFragment;
import com.cjj.mousepaint.fragment.HomeFragment;
import com.cjj.mousepaint.fragment.SubscribeFragment;
import com.cjj.mousepaint.utils.ScreenUtil;
import com.cjj.mousepaint.utils.StatusBarCompat;
import com.cjj.mousepaint.utils.VersionUtil;
import com.mingle.entity.MenuEntity;
import com.mingle.sweetpick.BlurEffect;
import com.mingle.sweetpick.Delegate;
import com.mingle.sweetpick.RecyclerViewDelegate;
import com.mingle.sweetpick.SweetSheet;
import com.nineoldandroids.animation.ObjectAnimator;
import java.util.ArrayList;
import butterknife.Bind;
import butterknife.ButterKnife;
import io.codetail.animation.SupportAnimator;
import io.codetail.animation.ViewAnimationUtils;
import io.codetail.animation.arcanimator.ArcAnimator;
import io.codetail.animation.arcanimator.Side;
package com.cjj.mousepaint;





public class HomeActivity extends AppCompatActivity implements OnClickListener {

    private FragmentManager mFragmentManager;
    private FragmentTransaction mFragmentTransaction;
    private String hideTag;

    private HomeFragment mHomeFragment;
    private CategoryFragment mCategoryFragment;
    private SubscribeFragment mSubscribeFragment;