自定义ViewGroup--标题条加内容页的布局方式

来源:互联网 发布:java都能做什么 编辑:程序博客网 时间:2024/04/30 05:14

自定义ViewGroup--标题条加内容页的布局方式


效果就是:

xxxxxxxxxxxxxxxxxxxxxxxxxxxx

|||||||||||||||||||||||||||||||||||||||||||||

||||||||||||||||||||||||||||||||||||||||||||||

|||||||||||||||||||||||||||||||||||||||||||||

|||||||||||||||||||||||||||||||||||||||||||||||

||||||||||||||||||||||||||||||||||||||||||||||


主要修改是在 onLayout进行布局,

    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int offset = getMeasuredWidth() - getPaddingLeft() - getPaddingRight()
                - (mCountX * mCellWidth);
        int left = getPaddingLeft() + (int) Math.ceil(offset / 2f);
        int top = getPaddingTop();
        int count = getChildCount();


        DisplayMetrics dm = mContext.getResources().getDisplayMetrics();
        int offset_hp = DynamicGrid.pxFromDp(40,dm);
        View child0 = getChildAt(0);
        if (child0.getVisibility() == GONE) {
            offset_hp = 0;
        }

  //两个子view,title固定高度,可动态决定是否显示
       for (int i = 0; i < count; i++) {
            View child = getChildAt(i);

            //child.layout(left, top, left + r - l, top + b - t);
            if(i == 1){
              child.layout(left, top+offset_hp, left + r - l, top + b - t); 
            }else{
              if (child.getVisibility() != GONE) {
                child.layout(left, top, left + r - l, offset_hp);
              }
            }
        }
    }


onMeasure的参考代码如下

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        LauncherAppState app = LauncherAppState.getInstance();
        DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();


        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize =  MeasureSpec.getSize(heightMeasureSpec);
        int childWidthSize = widthSize - (getPaddingLeft() + getPaddingRight());
        int childHeightSize = heightSize - (getPaddingTop() + getPaddingBottom());


        int newWidth = childWidthSize;
        int newHeight = childHeightSize;


        
        int count = getChildCount();
        int maxWidth = 0;
        int maxHeight = 0;
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(newWidth,
                    MeasureSpec.EXACTLY);
            int childheightMeasureSpec = MeasureSpec.makeMeasureSpec(newHeight,
                    MeasureSpec.EXACTLY);
            child.measure(childWidthMeasureSpec, childheightMeasureSpec);




            maxWidth = Math.max(maxWidth, child.getMeasuredWidth());
            maxHeight = Math.max(maxHeight, child.getMeasuredHeight());
        }
    }

0 0
原创粉丝点击