public class MaterialRefreshLayout extends FrameLayout {

    public static final String Tag = "cjj_log";

    private MaterialHeadView materialHeadView;

    private MaterialFoodView materialFoodView;

    private boolean isOverlay;

    private int waveType;

    private int DEFAULT_WAVE_HEIGHT = 140;

    private int HIGHER_WAVE_HEIGHT = 180;

    private int DEFAULT_HEAD_HEIGHT = 70;

    private int hIGHER_HEAD_HEIGHT = 100;

    private int DEFAULT_PROGRESS_SIZE = 50;

    private int BIG_PROGRESS_SIZE = 56;

    private int PROGRESS_STOKE_WIDTH = 3;

    private int waveColor;

    protected float mWaveHeight;

    protected float mHeadHeight;

    private View mChildView;

    protected FrameLayout mHeadLayout;

    protected boolean isRefreshing;

    private float mTouchY;

    private float mCurrentY;

    private DecelerateInterpolator decelerateInterpolator;

    private float headHeight;

    private float waveHeight;

    private int[] colorSchemeColors;

    private int colorsId;

    private int progressTextColor;

    private int progressValue,progressMax;

    private boolean showArrow;

    private int textType;

    private MaterialRefreshListener refreshListener;

    private boolean showProgressBg;

    private int progressBg;

    private boolean isShowWave;

    private int progressSizeType;

    private int progressSize = 0;

    private boolean isLoadMoreing;

    private boolean isLoadMore;

    public MaterialRefreshLayout(Context context) {
        this(context, null, 0);
    }

    public MaterialRefreshLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MaterialRefreshLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    private void init(Context context, AttributeSet attrs, int defstyleAttr) {
        if (isInEditMode()) {
            return;
        }

        if (getChildCount() > 1) {
            throw new RuntimeException("can only have one child widget");
        }

        decelerateInterpolator = new DecelerateInterpolator(10);


        TypedArray t = context.obtainStyledAttributes(attrs, R.styleable.MaterialRefreshLayout, defstyleAttr, 0);
        isOverlay = t.getBoolean(R.styleable.MaterialRefreshLayout_overlay,false);
        /**attrs for materialWaveView*/
        waveType = t.getInt(R.styleable.MaterialRefreshLayout_wave_height_type, 0);
        if (waveType == 0) {
            headHeight = DEFAULT_HEAD_HEIGHT;
            waveHeight = DEFAULT_WAVE_HEIGHT;
            MaterialWaveView.DefaulHeadHeight = DEFAULT_HEAD_HEIGHT;
            MaterialWaveView.DefaulWaveHeight = DEFAULT_WAVE_HEIGHT;
        } else {
            headHeight = hIGHER_HEAD_HEIGHT;
            waveHeight = HIGHER_WAVE_HEIGHT;
            MaterialWaveView.DefaulHeadHeight = hIGHER_HEAD_HEIGHT;
            MaterialWaveView.DefaulWaveHeight = HIGHER_WAVE_HEIGHT;
        }
        waveColor = t.getColor(R.styleable.MaterialRefreshLayout_wave_color, Color.WHITE);
        isShowWave = t.getBoolean(R.styleable.MaterialRefreshLayout_wave_show, true);

        /**attrs for circleprogressbar*/
        colorsId = t.getResourceId(R.styleable.MaterialRefreshLayout_progress_colors, R.array.material_colors);
        colorSchemeColors = context.getResources().getIntArray(colorsId);
        showArrow = t.getBoolean(R.styleable.MaterialRefreshLayout_progress_show_arrow, true);
        textType = t.getInt(R.styleable.MaterialRefreshLayout_progress_text_visibility, 1);
        progressTextColor = t.getColor(R.styleable.MaterialRefreshLayout_progress_text_color, Color.BLACK);
        progressValue = t.getInteger(R.styleable.MaterialRefreshLayout_progress_value, 0);
        progressMax = t.getInteger(R.styleable.MaterialRefreshLayout_progress_max_value, 100);
        showProgressBg = t.getBoolean(R.styleable.MaterialRefreshLayout_progress_show_circle_backgroud, true);
        progressBg = t.getColor(R.styleable.MaterialRefreshLayout_progress_backgroud_color, CircleProgressBar.DEFAULT_CIRCLE_BG_LIGHT);
        progressSizeType = t.getInt(R.styleable.MaterialRefreshLayout_progress_size_type,0);
        if(progressSizeType == 0)
        {
            progressSize = DEFAULT_PROGRESS_SIZE;
        }else {
            progressSize = BIG_PROGRESS_SIZE;
        }
        isLoadMore = t.getBoolean(R.styleable.MaterialRefreshLayout_isLoadMore,false);
        t.recycle();
    }


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

        Context context = getContext();

        FrameLayout headViewLayout = new FrameLayout(context);
        LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0);
        layoutParams.gravity = Gravity.TOP;
        headViewLayout.setLayoutParams(layoutParams);

        mHeadLayout = headViewLayout;

        this.addView(mHeadLayout);

        mChildView = getChildAt(0);

        if (mChildView == null) {
            return;
        }

        setWaveHeight(Util.dip2px(context, waveHeight));
        setHeaderHeight(Util.dip2px(context, headHeight));

        materialHeadView = new MaterialHeadView(context);
        materialHeadView.setWaveColor(isShowWave ? waveColor : Color.WHITE);
        materialHeadView.showProgressArrow(showArrow);
        materialHeadView.setProgressSize(progressSize);
        materialHeadView.setProgressColors(colorSchemeColors);
        materialHeadView.setProgressStokeWidth(PROGRESS_STOKE_WIDTH);
        materialHeadView.setTextType(textType);
        materialHeadView.setProgressTextColor(progressTextColor);
        materialHeadView.setProgressValue(progressValue);
        materialHeadView.setProgressValueMax(progressMax);
        materialHeadView.setIsProgressBg(showProgressBg);
        materialHeadView.setProgressBg(progressBg);
        setHeaderView(materialHeadView);

        materialFoodView = new MaterialFoodView(context);
        LayoutParams layoutParams2 = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, Util.dip2px(context,hIGHER_HEAD_HEIGHT));
        layoutParams2.gravity = Gravity.BOTTOM;
        materialFoodView.setLayoutParams(layoutParams2);
        materialFoodView.showProgressArrow(showArrow);
        materialFoodView.setProgressSize(progressSize);
        materialFoodView.setProgressColors(colorSchemeColors);
        materialFoodView.setProgressStokeWidth(PROGRESS_STOKE_WIDTH);
        materialFoodView.setTextType(textType);
        materialFoodView.setProgressValue(progressValue);
        materialFoodView.setProgressValueMax(progressMax);
        materialFoodView.setIsProgressBg(showProgressBg);
        materialFoodView.setProgressBg(progressBg);
        materialFoodView.setVisibility(View.GONE);
        setFooderView(materialFoodView);
    }


    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (isRefreshing) return true;
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mTouchY = ev.getY();
                mCurrentY = mTouchY;
                break;
            case MotionEvent.ACTION_MOVE:
                float currentY = ev.getY();
                float dy = currentY - mTouchY;
                if (dy > 0 && !canChildScrollUp()) {
                    if (materialHeadView != null) {
                        materialHeadView.onBegin(this);
                    }
                    return true;
                }
                else if(dy<0 && !canChildScrollDown()&&isLoadMore)
                {
                    if(materialFoodView != null&&!isLoadMoreing)
                    {
                        soveLoadMoreLogic();
                    }
                    return super.onInterceptTouchEvent(ev);
                }
                break;
        }
        return super.onInterceptTouchEvent(ev);
    }

    private void soveLoadMoreLogic() {
        isLoadMoreing = true;
        materialFoodView.setVisibility(View.VISIBLE);
        materialFoodView.onBegin(this);
        materialFoodView.onRefreshing(this);
        if(refreshListener != null)
        {
            refreshListener.onRefreshLoadMore(MaterialRefreshLayout.this);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent e) {
        if (isRefreshing) {
            return super.onTouchEvent(e);
        }

        switch (e.getAction()) {
            case MotionEvent.ACTION_MOVE:
                mCurrentY = e.getY();
                float dy = mCurrentY - mTouchY;
                    dy = Math.min(mWaveHeight * 2, dy);
                    dy = Math.max(0, dy);
                    if (mChildView != null) {
                        float offsetY = decelerateInterpolator.getInterpolation(dy / mWaveHeight / 2) * dy / 2;
                        float fraction = offsetY / mHeadHeight;
                        mHeadLayout.getLayoutParams().height = (int) offsetY;
                        mHeadLayout.requestLayout();

                        if (materialHeadView != null) {
                            materialHeadView.onPull(this, fraction);

                        }
                        if (!isOverlay)
                            ViewCompat.setTranslationY(mChildView, offsetY);

                    }
                return true;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                if (mChildView != null) {
                    if (isOverlay) {
                        if (mHeadLayout.getLayoutParams().height > mHeadHeight) {

                            updateListener();

                            mHeadLayout.getLayoutParams().height = (int) mHeadHeight;
                            mHeadLayout.requestLayout();

                        } else {
                            mHeadLayout.getLayoutParams().height = 0;
                            mHeadLayout.requestLayout();
                        }

                    } else {
                        if (ViewCompat.getTranslationY(mChildView) >= mHeadHeight) {
                            createAnimatorTranslationY(mChildView, mHeadHeight, mHeadLayout);
                           updateListener();
                        } else {
                            createAnimatorTranslationY(mChildView, 0, mHeadLayout);
                        }
                    }

                }
                return true;
        }
        return super.onTouchEvent(e);
    }


    public void autoRefresh()
    {
        if(!isRefreshing)
        {
            updateListener();
            if(isOverlay)
            {
                mHeadLayout.getLayoutParams().height = (int) mHeadHeight;
                mHeadLayout.requestLayout();
            }else
            {
                createAnimatorTranslationY(mChildView, mHeadHeight, mHeadLayout);
            }
        }

    }

    public void autoRefreshLoadMore()
    {
        if(isLoadMore)
        {
            soveLoadMoreLogic();
        }else
        {
            throw new RuntimeException("you must  setLoadMore ture");
        }
    }

    public void updateListener()
    {
        isRefreshing = true;

        if (materialHeadView != null) {
            materialHeadView.onRefreshing(MaterialRefreshLayout.this);
        }

        if (refreshListener != null) {
            refreshListener.onRefresh(MaterialRefreshLayout.this);
        }

    }

    public void setLoadMore(boolean isLoadMore)
    {
        this.isLoadMore = isLoadMore;
    }

    public void setProgressColors(int[] colors)
    {
        this.colorSchemeColors = colors;
    }

    public void setShowArrow(boolean showArrow)
    {
        this.showArrow = showArrow;
    }

    public void setShowProgressBg(boolean showProgressBg)
    {
        this.showProgressBg = showProgressBg;
    }

    public void setWaveColor(int waveColor)
    {
        this.waveColor = waveColor;
    }

    public void setWaveShow(boolean isShowWave){
        this.isShowWave = isShowWave;
    }

    public void setIsOverLay(boolean isOverLay)
    {
        this.isOverlay = isOverLay;
    }

    public void setProgressValue(int progressValue)
    {
        this.progressValue = progressValue;
        materialHeadView.setProgressValue(progressValue);
    }

    public void createAnimatorTranslationY(final View v, final float h, final FrameLayout fl) {
        ViewPropertyAnimatorCompat viewPropertyAnimatorCompat = ViewCompat.animate(v);
        viewPropertyAnimatorCompat.setDuration(200);
        viewPropertyAnimatorCompat.setInterpolator(new DecelerateInterpolator());
        viewPropertyAnimatorCompat.translationY(h);
        viewPropertyAnimatorCompat.start();
        viewPropertyAnimatorCompat.setUpdateListener(new ViewPropertyAnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(View view) {
                float height = ViewCompat.getTranslationY(v);
                fl.getLayoutParams().height = (int) height;
                fl.requestLayout();
            }
        });
    }

    /**
     * @return Whether it is possible for the child view of this layout to
     * scroll up. Override this if the child view is a custom view.
     */
    public boolean canChildScrollUp() {
        if (mChildView == null) {
            return false;
        }
        if (Build.VERSION.SDK_INT < 14) {
            if (mChildView instanceof AbsListView) {
                final AbsListView absListView = (AbsListView) mChildView;
                return absListView.getChildCount() > 0
                        && (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0)
                        .getTop() < absListView.getPaddingTop());
            } else {
                return ViewCompat.canScrollVertically(mChildView, -1) || mChildView.getScrollY() > 0;
            }
        } else {
            return ViewCompat.canScrollVertically(mChildView, -1);
        }
    }

    public boolean canChildScrollDown() {
        if (mChildView == null) {
            return false;
        }
        if (android.os.Build.VERSION.SDK_INT < 14) {
            if (mChildView instanceof AbsListView) {
                final AbsListView absListView = (AbsListView) mChildView;
                if (absListView.getChildCount()>0)
                {
                    int lastChildBottom = absListView.getChildAt(absListView.getChildCount() - 1).getBottom();
                    return absListView.getLastVisiblePosition() == absListView.getAdapter().getCount() - 1 && lastChildBottom <= absListView.getMeasuredHeight();
                }else
                {
                    return false;
                }

            } else {
                return ViewCompat.canScrollVertically(mChildView, 1) || mChildView.getScrollY() > 0;
            }
        } else {
            return ViewCompat.canScrollVertically(mChildView, 1);
        }
    }

    public void setWaveHigher() {
        headHeight = hIGHER_HEAD_HEIGHT;
        waveHeight = HIGHER_WAVE_HEIGHT;
        MaterialWaveView.DefaulHeadHeight = hIGHER_HEAD_HEIGHT;
        MaterialWaveView.DefaulWaveHeight = HIGHER_WAVE_HEIGHT;
    }

    public void finishRefreshing() {
        if (mChildView != null) {
            ViewPropertyAnimatorCompat viewPropertyAnimatorCompat = ViewCompat.animate(mChildView);
            viewPropertyAnimatorCompat.setDuration(200);
            viewPropertyAnimatorCompat.y(ViewCompat.getTranslationY(mChildView));
            viewPropertyAnimatorCompat.translationY(0);
            viewPropertyAnimatorCompat.setInterpolator(new DecelerateInterpolator());
            viewPropertyAnimatorCompat.start();

            if (materialHeadView != null) {
                materialHeadView.onComlete(MaterialRefreshLayout.this);
            }

            if (refreshListener != null) {
                refreshListener.onfinish();
            }
        }
        isRefreshing = false;
        progressValue = 0;
        setProgressValue(0);
    }

    public void finishRefresh()
    {
        this.postDelayed(new Runnable() {
            @Override
            public void run() {
                finishRefreshing();
            }
        },300);
    }

    public void finishRefreshLoadMore()
    {
        this.post(new Runnable() {
            @Override
            public void run() {
                if (materialFoodView != null && isLoadMoreing) {
                    isLoadMoreing = false;
                    materialFoodView.onComlete(MaterialRefreshLayout.this);
                }
            }
        });

    }

    public void setHeaderView(final View headerView) {
        post(new Runnable() {
            @Override
            public void run() {
                mHeadLayout.addView(headerView);
            }
        });
    }

    public void setFooderView(final View fooderView) {
        this.addView(fooderView);
    }


    public void setWaveHeight(float waveHeight) {
        this.mWaveHeight = waveHeight;
    }

    public void setHeaderHeight(float headHeight) {
        this.mHeadHeight = headHeight;
    }

    public void setMaterialRefreshListener(MaterialRefreshListener refreshListener) {
        this.refreshListener = refreshListener;
    }

} public abstract class MaterialRefreshListener {
    public void onfinish(){};
    public abstract void onRefresh(MaterialRefreshLayout materialRefreshLayout);
    public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout){};
} public class CallbackListener<T> extends BaseListener<T>{

    @Override
    public void onError(Exception e) {

    }

    @Override
    public void onSuccess(T result) {

    }

    @Override
    public void onStringResult(String result) {

    }

    @Override
    public void onDownloadFinish(String path) {

    }

    @Override
    public void onDownloadProgress(int progress) {

    }


} public class DetialActivity extends AppCompatActivity implements View.OnClickListener,AdapterView.OnItemClickListener{
    @Bind(R.id.toolbar)
    Toolbar mToolbar;
    @Bind(R.id.collapsing_toolbar)
    CollapsingToolbarLayout mCollapsingToolbarLayout;
    @Bind(R.id.backdrop)
    ImageView mImageView;
    @Bind(R.id.lv_detial)
    GridView mListView;
    @Bind(R.id.ns_view)
    NestedScrollView mNestedScrollView;
    @Bind(R.id.fab_sub)
    FloatingActionButton fab_sub;

    private boolean isHaveBottom = false;
    private String id ;
    private DetialBookAdapter mDetialBookAdapter;
    private boolean isLoadMore = false;
    private List<DetialComicBookModel.ReturnEntity.ListEntity> list;
    private int PageIndex = 0;
    private boolean isSub = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_detial);
        ButterKnife.bind(this);
        StatusBarCompat.compat(this, getResources().getColor(R.color.brownness));
        id = getIntent().getStringExtra("bookId");
        mNestedScrollView.setOnTouchListener(new TouchListenerImpl());
        setSupportActionBar(mToolbar);
        fab_sub.setOnClickListener(this);
        mListView.setOnItemClickListener(this);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        getBookComicData();


    }
    private void getBookComicData() {
        AppDao.getInstance().getBookComicData(id, String.valueOf(PageIndex), new CallbackListener<DetialComicBookModel>() {
            @Override
            public void onSuccess(DetialComicBookModel result) {
                super.onSuccess(result);
                showView(result);
            }
        });
    }

    private void showView(DetialComicBookModel result) {
        if(!isLoadMore)
        {
            list = result.Return.List;
            mCollapsingToolbarLayout.setTitle(result.Return.ParentItem.Title);
            Glide.with(this).load(result.Return.ParentItem.FrontCover).centerCrop().into(mImageView);
            mDetialBookAdapter = new DetialBookAdapter(DetialActivity.this,list );
            mListView.setAdapter(mDetialBookAdapter);

        }else
        {
            list.addAll(result.Return.List);
            mDetialBookAdapter.updateData(list);
            isLoadMore = false;
            isHaveBottom = false;
        }

        if(SPUtils.getObject(MosuePaintAppication.UserInfo.email+"id"+id,String.class,"-1").equals(id))
        {
            fab_sub.setImageResource(R.drawable.ic_done);
            isSub = false;
        }else
        {
            isSub = true;
            fab_sub.setImageResource(R.drawable.ic_add_white_24dp);
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.fab_sub:
                    subComicBook();
                break;
        }
    }

    private void subComicBook() {
        if(id==null)
        {
            return;
        }
        AppDao.getInstance().subscribeBook(id,isSub,new CallbackListener<SubscribeModel>()
        {

            @Override
            public void onSuccess(SubscribeModel result) {
                super.onSuccess(result);
                if(isSub)
                {
                    Toast.makeText(DetialActivity.this,"订阅成功",Toast.LENGTH_SHORT).show();
                    SPUtils.saveObject(MosuePaintAppication.UserInfo.email + "id" + id, id);
                    fab_sub.setImageResource(R.drawable.ic_done);
                    isSub = false;
                }else
                {
                    Toast.makeText(DetialActivity.this,"已取消订阅",Toast.LENGTH_SHORT).show();
                    SPUtils.saveObject(MosuePaintAppication.UserInfo.email + "id" + id, "-2");
                    fab_sub.setImageResource(R.drawable.ic_add_white_24dp);
                    isSub = true;
                }
            }

            @Override
            public void onError(Exception e) {
                super.onError(e);
                Toast.makeText(DetialActivity.this,"操作失败",Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        handClick(HttpUrl.URL_IMG_CHAPTER + mDetialBookAdapter.getItem(position).Id, "123");

    }

    private void handClick(String url,String title) {
        Intent intent = new Intent(this, WebActivity.class);
        intent.putExtra(WebActivity.EXTRA_URL, url);
        intent.putExtra(WebActivity.EXTRA_TITLE,title);
        startActivity(intent);
    }

    private class TouchListenerImpl implements View.OnTouchListener {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            switch (motionEvent.getAction()) {
                case MotionEvent.ACTION_DOWN:

                    break;
                case MotionEvent.ACTION_MOVE:
                    int scrollY=view.getScrollY();
                    int height=view.getHeight();
                    int scrollViewMeasuredHeight=mNestedScrollView.getChildAt(0).getMeasuredHeight();
                    if(scrollY==0){
                        System.out.println("滑动到了顶端 view.getScrollY()="+scrollY);
                    }
                    if((scrollY+height)==scrollViewMeasuredHeight){
                        if(!isHaveBottom)
                        {
                            isLoadMore = true;
                            PageIndex += 1;
                            getBookComicData();
                        }
                        isHaveBottom = true;

                    }
                    break;

                default:
                    break;
            }
            return false;
        }

    };
} public class CategoryDetialAdapter extends BaseAdapter {

    private Activity context;
    private List<CategoryModel.ReturnEntity.ListEntity> list;
    private ViewHolder mHolder;
    private int selectIndex = 0;

    public CategoryDetialAdapter(Activity context, List<CategoryModel.ReturnEntity.ListEntity> list) {
        this.context = context;
        this.list = list;
    }

    public void  updateData(List<CategoryModel.ReturnEntity.ListEntity> list)
    {
        this.list = list;
        this.notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public CategoryModel.ReturnEntity.ListEntity getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        mHolder = new ViewHolder();
        convertView = ViewHolderUtils.loadingConvertView(parent.getContext(), convertView, R.layout.item_category_detial, ViewHolder.class);
        mHolder = (ViewHolder) convertView.getTag();
        mHolder.tv_comic_title.setText(list.get(position).Title);
        mHolder.tv_comic_intro.setText(list.get(position).Explain);
        mHolder.tv_num_last.setText(list.get(position).Author);
        if(null != list.get(position).LastChapter&& !"null".equals(list.get(position).LastChapter.ChapterNo))
        mHolder.tv_comic_status.setText(list.get(position).LastChapter.ChapterNo+" 话");
        Glide.with(context).load(list.get(position).FrontCover).centerCrop().into(mHolder.iv_zone_item);
        return convertView;
    }



    public static class ViewHolder {
        public ImageView iv_zone_item;
        public TextView tv_comic_title,tv_comic_intro,tv_num_last,tv_comic_status;
    }
} public class NormalListView extends ListView{
	
	private boolean isAutoSetNumColumns = true;
	private int horizontalSpacing = 0;
    private int columnWidth = 0;
    private boolean isScroll = false;

	public NormalListView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}
	
  
    @Override 
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 

        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); 
        
        super.onMeasure(widthMeasureSpec,expandSpec); 
    }

//	@Override
//	public void setAdapter(ListAdapter adapter) {
//	
//		if(isScroll)
//		{
//		
//		int gridViewWidth = 0;
//		int adapterCount = adapter.getCount();
//		
//		if(columnWidth == 0)
//		{
//			for(int i = 0 ; i< adapter.getCount();i++)
//		    {
//			View rowView = adapter.getView(i,null,null);
//	        measureView(rowView);
//			gridViewWidth += rowView.getMeasuredWidth();
//		    }
//		}
//		else
//		{
//			gridViewWidth += columnWidth*adapterCount;
//		}
//
//		
//		this.setLayoutParams(new LinearLayout.LayoutParams(gridViewWidth,LayoutParams.WRAP_CONTENT));
//	
//		}
//		
//		super.setAdapter(adapter);
//	} 
//	
//	
//	private void measureView(View child) 
//	{
//		 ViewGroup.LayoutParams p = child.getLayoutParams();
//	       if (p == null) {
//	           p = new ViewGroup.LayoutParams(
//	                   ViewGroup.LayoutParams.FILL_PARENT,
//	                   ViewGroup.LayoutParams.WRAP_CONTENT);
//	       }
//
//	       int childWidthSpec = ViewGroup.getChildMeasureSpec(0,
//	               0 + 0, p.width);
//	       int lpHeight = p.height;
//	       int childHeightSpec;
//	       if (lpHeight > 0) {
//	           childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
//	       } else {
//	           childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
//	       }
//	       child.measure(childWidthSpec, childHeightSpec);
//	}
//    

} public class AppDao {

    private static final String FromType = "2";

    private static AppDao instance;

    public static AppDao getInstance() {
        if (instance == null) {
            instance = new AppDao();
        }
        return instance;
    }

    private AppDao() {
    }

    public Map<String,String> createMap()
    {
        Map<String,String> map = new HashMap<>();
        return map;
    }

    /**
     * 获取最新漫画
     * @param listener
     */
    public void getAllBook(CallbackListener<AllBookModels> listener)
    {
        Http.post(HttpUrl.GET_ALL_BOOK, null, listener);
    }

    /**
     * 获取最新推荐漫画
     */
    public void getRecommendBook(String Recommended,String Subscribe,CallbackListener<AllBookModels> listener)
    {
        Map<String,String> map = createMap();
        map.put("Recommended", Recommended);
        map.put("Subscribe",Subscribe);
        Http.post(HttpUrl.URL_RECOMMEND,map,listener);
    }

    /**
     * 本周更新
     */
    public void getWeekBook(String Days,String Subscribe,CallbackListener<AllBookModels> listener)
    {
        Map<String,String> map = createMap();
        map.put("Days", Days);
        map.put("Subscribe",Subscribe);
        Http.post(HttpUrl.URL_WEEK_SEVEN,map,listener);
    }


    /**
     * 注册
     * @param email
     * @param pass
     * @param listener
     */
    public void userRegister(String email,String pass,CallbackListener<RegisterModel> listener)
    {
        Map<String,String> map = createMap();
        map.put("Email", email);
        map.put("Password", EncryptionUtils.createMd5(pass));
        map.put("FromType",FromType);
        Http.post(HttpUrl.URL_USER_REGISTER,map,listener);
    }

    /**
     * 登录
     * @param email
     * @param pass
     * @param listener
     */
    public void userLogin(String email,String pass,CallbackListener<LoginModel> listener)
    {
        Map<String,String> map = createMap();
        map.put("Email", email);
        map.put("Password", EncryptionUtils.createMd5(pass));
        map.put("FromType",FromType);
        Http.post(HttpUrl.URL_USER_LOGIN,map,listener);
    }

    /**
     * 获取某章节的图片信息
     */
    public void getChapterImg(String id,CallbackListener<String> listener)
    {
        Http.get(HttpUrl.URL_IMG_CHAPTER + id, listener);
    }

    /**
     * 订阅漫画
     * @param id
     * @param flag
     * @param listener
     */
    public void subscribeBook(String id,boolean flag,CallbackListener<SubscribeModel> listener)
    {
        Map<String,String> map = createMap();
        map.put("isSubscribe", String.valueOf(flag));
        map.put("bookid",id);
        Http.post(HttpUrl.URL_USER_SUBSCRIBE, map, listener);
    }


    /**
     * 获取用户订阅的列表
     * @param Subscribe
     * @param listener
     */
    public void subscribeByUser(String Subscribe,CallbackListener<AllBookModels> listener)
    {
        Map<String,String> map = createMap();
        map.put("Subscribe", Subscribe);
        Http.post(HttpUrl.URL_SUBCRIBE_USER, map, listener);
    }

    /**
     * 获取幻灯片接口
     */
    public void getSlideData(CallbackListener<AdvModel> listener)
    {
        Http.get(HttpUrl.URL_SLIDE_DATA, listener);
    }


    /**
     * 获取某一分类30条记录
     * ClassifyId分类标识，0热血，1国产，2同人，3鼠绘
     * Size每次获取的消息条数，最大值为30
     * PageIndex获取第几页的数据
     */
    public void getCategoryData(String ClassifyId,String Size,String PageIndex,CallbackListener<CategoryModel> listener)
    {
        Map<String,String> map = createMap();
        map.put("ClassifyId", ClassifyId);
        map.put("Size",Size);
        map.put("PageIndex",PageIndex);
        Http.post(HttpUrl.URL_CATEGORY_DATA, map, listener);
    }

    /**
     * 搜索动漫数据
     * @param Title
     * @param listener
     */
    public void searchComicData(String Title,CallbackListener<SearchComicModel> listener)
    {
        Map<String,String> map = createMap();
        try {
            map.put("Title", URLDecoder.decode(Title, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Http.post(HttpUrl.URL_SEARCH_DATA, map, listener);
    }

    public void getBookComicData(String id,String PageIndex,CallbackListener<DetialComicBookModel> listener)
    {
        Map<String,String> map = createMap();
        map.put("id",id);
        map.put("PageIndex",PageIndex);
        Http.post(HttpUrl.URL_COMIC_BOOK_DATA, map, listener);
    }


} public class RefreshEvent {

    public String category ;
    public MaterialRefreshLayout mMaterialRefreshLayout;

    public RefreshEvent(String category)
    {
        this.category = category;
    }

    public RefreshEvent(MaterialRefreshLayout materialRefreshLayout,String category)
    {
        this.category = category;
        this.mMaterialRefreshLayout = materialRefreshLayout;
    }
} public class RefreshFinishEvent {

    public String isFinish ;

    public RefreshFinishEvent()
    {

    }

    public RefreshFinishEvent(String isFinish)
    {
        this.isFinish = isFinish;
    }
} public class ViewPagerHeightEvent  {

    public int heith;
    public String vp;

    public ViewPagerHeightEvent(String vp,int heith) {
        this.vp = vp;
        this.heith = heith;
    }
} public class ViewSelectorLayout extends FrameLayout implements View.OnClickListener {


    private View contentView;//目标界面
    private View failView; //失败界面
    private View emptyView;//数据为空界面
    private View loadingView;//加载界面
    private TextView tv_reload;
    private TextView tv_not_data;
    private ReLoadCallbackListener callbackListener;

    public ViewSelectorLayout(Context context,View contentView) {
        super(context);
        this.contentView = contentView;
        initView();
        handleView();
    }

    public ViewSelectorLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public ViewSelectorLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    private void initView()
    {

        if(failView == null)
        {
            failView = inflaterView( R.layout.view_fail);
            tv_reload = (TextView) failView.findViewById(R.id.tv_reload);
            tv_reload.setOnClickListener(this);
        }

        if(emptyView == null)
        {
            emptyView = inflaterView( R.layout.view_empty);
            tv_not_data = (TextView) emptyView.findViewById(R.id.tv_empty);
        }

        if(loadingView==null)
        {
            loadingView = inflaterView( R.layout.view_loading);
        }

    }


    /**
     *装载器
     * @param layoutId
     * @return
     */
    private View inflaterView(int layoutId)
    {
        return LayoutInflater.from(getContext()).inflate(layoutId,null);
    }



    private void handleView()
    {
        add_AllView();
        hide_AllView();
    }

    private void add_AllView()
    {
        this.addView(failView);
        this.addView(emptyView);
        this.addView(loadingView);
        this.addView(contentView);
    }

    private void hide_AllView()
    {
        if(failView != null)
        {
            failView.setVisibility(INVISIBLE);
        }
        if(loadingView != null)
        {
            loadingView.setVisibility(INVISIBLE);
        }
        if(emptyView != null)
        {
            emptyView.setVisibility(INVISIBLE);
        }
        if(contentView != null)
        {
            contentView.setVisibility(INVISIBLE);
        }
    }

    public void show_ContentView()
    {
        if(contentView != null)
        {
            contentView.setVisibility(VISIBLE);
        }
        if(failView != null)
        {
            failView.setVisibility(INVISIBLE);
        }
        if(loadingView != null)
        {
            loadingView.setVisibility(INVISIBLE);
        }
        if(emptyView != null)
        {
            emptyView.setVisibility(INVISIBLE);
        }

    }

    public void show_FailView()
    {
        if(failView != null)
        {
            failView.setVisibility(VISIBLE);
        }
        if(loadingView != null)
        {
            loadingView.setVisibility(INVISIBLE);
        }
        if(emptyView != null)
        {
            emptyView.setVisibility(INVISIBLE);
        }
        if(contentView != null)
        {
            contentView.setVisibility(INVISIBLE);
        }
    }

    public void show_EmptyView()
    {
        if(emptyView != null)
        {
            emptyView.setVisibility(VISIBLE);
        }

        if(failView != null)
        {
            failView.setVisibility(INVISIBLE);
        }
        if(loadingView != null)
        {
            loadingView.setVisibility(INVISIBLE);
        }

        if(contentView != null)
        {
            contentView.setVisibility(INVISIBLE);
        }
    }

    public void show_LoadingView()
    {
        if(loadingView != null)
        {
            loadingView.setVisibility(VISIBLE);
        }
        if(failView != null)
        {
            failView.setVisibility(INVISIBLE);
        }
        if(emptyView != null)
        {
            emptyView.setVisibility(INVISIBLE);
        }
        if(contentView != null)
        {
            contentView.setVisibility(INVISIBLE);
        }
    }

    public void setReLoadCallbackListener(ReLoadCallbackListener callbackListener)
    {
        this.callbackListener = callbackListener;
    }

    @Override
    public void onClick(View v) {
        solveReLoad();
    }

    /**
     * 处理重新点击事件
     */
    private void solveReLoad()
    {
        if(NetUtils.isNetworkConnected(getContext()))
        {
            if(callbackListener != null)
            {
                this.callbackListener.onReLoadCallback();
            }else{
                throw new RuntimeException("You must be set setReLoadCallbackListener");
            }

        }
    }

}
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.cjj.listener.CallbackListener;
import com.cjj.mousepaint.DetialActivity;
import com.cjj.mousepaint.R;
import com.cjj.mousepaint.adapter.CategoryDetialAdapter;
import com.cjj.mousepaint.customview.NormalListView;
import com.cjj.mousepaint.dao.AppDao;
import com.cjj.mousepaint.events.RefreshEvent;
import com.cjj.mousepaint.events.RefreshFinishEvent;
import com.cjj.mousepaint.events.ViewPagerHeightEvent;
import com.cjj.mousepaint.model.CategoryModel;
import com.cjj.view.ViewSelectorLayout;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
package com.cjj.mousepaint.fragment;





/**
 * Created by Administrator on 2015/11/4.
 */
public class SamePeopleFragment extends BaseFragment  implements AdapterView.OnItemClickListener{
    private boolean isInit = false;
    private boolean isHaveLoadData = false;
    private int PageIndex = 0;
    private CategoryDetialAdapter mAdapter;
    private List<CategoryModel.ReturnEntity.ListEntity> mList;
    @Bind(R.id.lv_hot)
    NormalListView lv_hot;
    @Bind(R.id.pb)
    ProgressBar pb;
    private boolean isLoadMore = false;

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

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

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View v = inflater.inflate(R.layout.fragment_hot_book, null);
        ButterKnife.bind(this, v);
        isInit = true;
        return v;
    }

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

    }

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

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

    @Override
    protected void lazyLoad() {
        if (!isInit || !isVisible||isHaveLoadData) {
            return;
        }
        lv_hot.post(new Runnable() {
            @Override
            public void run() {

            }
        });

        lv_hot.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Log.i("tag", "same=" + lv_hot.getMeasuredHeight());
                EventBus.getDefault().post(new ViewPagerHeightEvent("same", lv_hot.getMeasuredHeight()));
            }
        });
        lv_hot.setOnItemClickListener(this);
        getCategoryData();
    }

    private void getCategoryData() {
        AppDao.getInstance().getCategoryData("2", "30", String.valueOf(PageIndex), new CallbackListener<CategoryModel>() {