1 首先做一个定义的View 继承RelativeLayout (举例用RelativeLayout 当然你可以用线性布局都无所谓)。
然后重写一下3个方法。下一步做过自定义属性动画的同学都应该知道。我们应该重写onMeasure()方法。在这个方法里面 我们会做几个事情:1 获取到屏幕的宽高。2 拿到控件的宽高。然后进行改变。下面是代码。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 测量高度
int width = View.MeasureSpec.getSize(widthMeasureSpec);
int height = View.MeasureSpec.getSize(heightMeasureSpec);
// 测量自控件的宽高 然后进行改变
int childCount = getChildCount();// 获取到下面的所有子控件
for (int i = 0; i < childCount; i++) {
View view = getChildAt(i);
float widthpercent = 0;
float heightpercent = 0;
ViewGroup.LayoutParams Params = view.getLayoutParams();
if (Params instanceof PercentLayout.LayoutParams) {
widthpercent = ((PercentLayout.LayoutParams) Params)
.getWidthPercent();
heightpercent = ((PercentLayout.LayoutParams) Params)
.getHeightPercent();
}
if (widthpercent != 0) {
Params.width = (int) (width * widthpercent);
Params.height = (int) (height * heightpercent);
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
2 但是做完上面的还是不够的。我们还需要复写generateLayoutParams()
@Override
public android.widget.RelativeLayout.LayoutParams generateLayoutParams(
AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
3 现在我们来写LayoutParams这个内部类
class LayoutParams extends RelativeLayout.LayoutParams {
private float widthPercent;
private float heightPercent;
public LayoutParams(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
TypedArray array = context.obtainStyledAttributes(attributeSet,
R.styleable.percentlayout);
heightPercent = array.getFloat(
R.styleable.percentlayout_layout_heightpercent,
heightPercent);
widthPercent = array
.getFloat(R.styleable.percentlayout_layout_widthpercent,
widthPercent);
array.recycle();// 释放掉
}
注意的是我们在这里继承的是这个RelativeLayout。如果你用LinLayout的也可以的 但是我们要和这个自定义的保持一致。我们做的是一个自定义RelativeLayout 的百分比布局。然后是把里面的方法都复写一次。
4 然后是布局文件。我自定义了一个attr文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="percentlayout">
<attr name="layout_widthpercent" format="float">0</attr>
<attr name="layout_heightpercent" format="float">0</attr>
</declare-styleable>
</resources>
5 看activity_main.xml布局
<?xml version="1.0" encoding="utf-8"?>
<com.example.percentlayout.PercentLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/com.example.percentlayout"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="Nice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_widthpercent="0.6"
android:layout_marginLeft="20px"
app:layout_heightpercent="0.8"
android:background="@android:color/holo_orange_dark"
/>
</com.example.percentlayout.PercentLayout>
注意地方是那个app 这个属性是没有的。是我们在头文件里面申明的当然 你也可以改成其他的
xmlns:app="http://schemas.android.com/apk/res/com.example.percentlayout"