歡迎大家下載我個(gè)人開發(fā)的app安琪花園
其基本思路是:
1. 通過自定義屬性,作用于PercentRelativeLayout的子控件上面
2. 重寫PercentRelativeLayout 靜態(tài)內(nèi)部類LayoutParams繼承自RelativeLayout.LayoutParams
3. 在重寫的LayoutParams里面解析出新增加的屬性
4. 重寫PercentRelatvieLayoutParams里面的generateLayoutParams(AttributeSet attrs)方法,并返回我們自己定義 的LayoutParams實(shí)例
5. 重寫percentRelativeLayout的onmeasure方法锋边,計(jì)算出控件的真正寬高。
接下來看一下具體的代碼
第一步:
<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實(shí)例
@Override
public RelativeLayout.LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
第五步: 重寫onMeasure方法, 計(jì)算出真正的寬高
@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地址
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者