android 百分比布局
2019-07-08 本文已影响0人
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);
}