android 百分比布局

欢迎大家下载我个人开发的app安琪花园

其基本思路是:

1. 通过自定义属性,作用于PercentRelativeLayout的子控件上面 
2. 重写PercentRelativeLayout 静态内部类LayoutParams继承自RelativeLayout.LayoutParams
3. 在重写的LayoutParams里面解析出新增加的属性
4. 重写PercentRelatvieLayoutParams里面的generateLayoutParams(AttributeSet attrs)方法,并返回我们自己定义 的LayoutParams实例
5. 重写percentRelativeLayout的onmeasure方法,计算出控件的真正宽高。

接下来看一下具体的代码

第一步:
<declare-styleable name="Percent">
        <attr name="width_percent" format="float"></attr>
       <attr name="height_percent" format="float"></attr>
    </declare-styleable>
第二步, 第三步: 位于自定义控件PercentRelativeLayout下面
public static class LayoutParams extends RelativeLayout.LayoutParams {

        public float width;
        public float height;

        public LayoutParams(Context c, AttributeSet attrs) {
            super(c, attrs);
            TypedArray array = c.obtainStyledAttributes(attrs, R.styleable.Percent);
            width = array.getFloat(R.styleable.Percent_width_percent, 0);
            height = array.getFloat(R.styleable.Percent_height_percent, 0);
            array.recycle();
        }

    }
第四步:返回了自己写的LayoutParams实例

    @Override
    public RelativeLayout.LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new LayoutParams(getContext(), attrs);
    }
第五步: 重写onMeasure方法,  计算出真正的宽高
@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int count = getChildCount();
        for(int i = 0; i < count; i++){
            View view = getChildAt(i);
            ViewGroup.LayoutParams params = view.getLayoutParams();
            if(checkLayoutParams(params)){
                LayoutParams params1 = (LayoutParams) params;
                if(params1.width > 0){
                    params.width = (int) (width * params1.width);
                }

                if(params1.height > 0){
                    params.height = (int) (height * params1.height);
                }
                view.setLayoutParams(params);
            }
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

github地址

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,656评论 1 32
  • 年轻时以为生活是人与人互相征服的过程,是人征服世界的过程; 再长大以为生活是人与人互相驯服的过程,是人被世界驯化的...
    Abbie_Y阅读 203评论 0 0
  • 富爸爸答应和我们见面交谈。于是,我我和迈克便在周六的上午来到迈克家,等着与富爸爸见面,希望他能教我们挣钱的方法...
    Windy杨阅读 134评论 2 0
  • 黄昏街头漫步,视线沿着街道由近到远处,最后汇成一点。楼盘从近到远呈现出阶梯排列。物体的渐变很容易看得到。 然而散步...
    PageWong阅读 807评论 1 1

友情链接更多精彩内容