android软件百分比怎么实现,android 百分比布局

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

其基本思路是:

1. 通过自定义属性,作用于PercentRelativeLayout的子控件上面

2. 重写PercentRelativeLayout 静态内部类LayoutParams继承自RelativeLayout.LayoutParams

3. 在重写的LayoutParams里面解析出新增加的属性

4. 重写PercentRelatvieLayoutParams里面的generateLayoutParams(AttributeSet attrs)方法,并返回我们自己定义 的LayoutParams实例

5. 重写percentRelativeLayout的onmeasure方法,计算出控件的真正宽高。

接下来看一下具体的代码

第一步:

第二步, 第三步: 位于自定义控件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);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值