1 首先作一個定義的View 繼承RelativeLayout (舉例用RelativeLayout 固然你能夠用線性佈局都無所謂)。android
而後重寫一下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();
}app
if (widthpercent != 0) {
Params.width = (int) (width * widthpercent);
Params.height = (int) (height * heightpercent);
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}ide
2 可是作完上面的仍是不夠的。咱們還須要複寫generateLayoutParams()佈局
@Override
public android.widget.RelativeLayout.LayoutParams generateLayoutParams(
AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}動畫
3 如今咱們來寫LayoutParams這個內部類.net
class LayoutParams extends RelativeLayout.LayoutParams {
private float widthPercent;
private float heightPercent;orm
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();// 釋放掉
}xml
注意的是咱們在這裏繼承的是這個RelativeLayout。若是你用LinLayout的也能夠的 可是咱們要和這個自定義的保持一致。咱們作的是一個自定義RelativeLayout 的百分比佈局。而後是把裏面的方法都複寫一次。繼承
4 而後是佈局文件。我自定義了一個attr文件utf-8
<?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"