---
title: "Android自定义Layout"
author: "owennet"
date: "2010-08-23T14:22:10Z"
tags: []
categories: ["移动开发"]
slug: "android-layout"
draft: false
lastmod: "2010-08-23T14:22:10Z"
id: 745019
url: "https://owennet.iteye.com/blog/745019"
---

在开发Android过程中，有时已有的Loyout布局不能完全满足设计需求，这时需要在已有的Layout基础上上进行扩展，以达到通过配置文件描述布局的设计原则。

首先第一一个布局类，重写其onDraw方法。

```
public static class iRelativeLayout extends RelativeLayout
	{
		private Paint	mPaint;
		private Rect	mRect;

		public iRelativeLayout( Context context, AttributeSet attrs ) {
			super(context, attrs);

			mRect = new Rect();
			mPaint = new Paint();

			mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
			mPaint.setColor(0xFFCBD2D8);
		}

		@Override
		protected void onDraw(Canvas canvas)
		{
			super.onDraw(canvas);

			canvas.drawColor(0xFFC5CCD4);

			this.getDrawingRect(mRect);

			for (int i = 0; i < mRect.right; i += 7)
			{
				canvas.drawRect(mRect.left + i, mRect.top, mRect.left + i + 2,
						mRect.bottom, mPaint);
			}

		}
	}
```

 其次，在布局配置文件中引用：

&lt;?xml version="1.0" encoding="utf-8"?&gt;

 

&lt;view xmlns:android="http://schemas.android.com/apk/res/android"

class="iRelativeLayout"

    android:orientation="vertical"

    android:layout\_width="fill\_parent"

    android:layout\_height="fill\_parent"

    android:background = "#C5CCD4FF"

&gt;

&lt;LinearLayout

android:id = "@+id/TabLayout\_One"

android:layout\_width = "fill\_parent"

android:layout\_height = "fill\_parent"

android:layout\_above = "@+id/Tabs"

&gt;

&lt;ScrollView android:layout\_width="fill\_parent" android:layout\_height="wrap\_content"&gt;

&lt;RelativeLayout

android:layout\_width = "fill\_parent"

android:layout\_height = "fill\_parent"

android:visibility = "visible"

&gt;

&lt;Button

android:id = "@+id/ButtonOne"

android:layout\_width = "wrap\_content"

android:layout\_height = "fill\_parent"

android:text = "h3h3h3"

/&gt;

&lt;Button

android:id = "@+id/ButtonTwo"

android:layout\_width = "wrap\_content"

android:layout\_height = "wrap\_content"

android:text = "11222"

android:layout\_below ="@+id/ButtonOne"

/&gt;

&lt;Button

android:id = "@+id/ButtonThree"

android:layout\_width = "wrap\_content"

android:layout\_height = "wrap\_content"

android:text = "wass"

android:layout\_below ="@+id/ButtonTwo"

/&gt;

&lt;/RelativeLayout&gt;

&lt;/ScrollView&gt;

&lt;/LinearLayout&gt;

&lt;/view&gt;

最后，和其他布局一样使用即可。