您的位置:首页 > 其它

自定义View简单小例子

2015-04-23 10:37 375 查看
在开发过程中,尽管Android系统提供了非常多的控件给我们使用,但是还是不能满足我们人类的需求,感觉我们确实在贪婪了,呵呵!这个时候,我们可能就要用到自定义控件,以及自定义属性,应该怎么操作呢?

一般要按照以下几个步骤来操作:

1,继承View或其它控件,重写构造函数onDraw,onMeasure,onTouch等函数。

2,自定义属性的话,就需要在values下建立attrs.xml,在其中定义你需要的属性,详细的属性类型可以参考文章http://www.jb51.net/article/32172.htm

3,使用到自定义View的xml布局文件中需要加入xmlns:前缀="http://schemas.android.com/apk/res/自定义View所在包路径",如我用到的前缀是xmlns:app。使用自定义属性的时候,也是使用前缀:属性名。

下面按照步骤来个小例子:

----------定义View,重写onDraw()---------------

public class DefaultView extends View {

/**画笔paint,用与设置抽绘制图案的颜色及样式*/

private Paint mPaint;

/**构造方法*/

public DefaultView(Context context) {

super(context);

}

public DefaultView(Context context, AttributeSet attrs) {

super(context, attrs);

mPaint = new Paint();

/**TypedArray用来存放由context.obtainStyledAttributes获得的属性的数组

*使用完成后,务必要调用recycle方法

*/

TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.DefaultView);

/**取得颜色值,否则用默认值*/

int textColor = array.getColor(R.styleable.DefaultView_textColor, 0XFF00FF00);

/**取得文字大小,否则用默认值*/

float textSize = array.getDimension(R.styleable.DefaultView_textSize, 36);

mPaint.setColor(textColor);

mPaint.setTextSize(textSize);

/**如果不调用recycle()方法,则这次的设定会对下次的使用造成影响*/

array.recycle();

}

/**重写onDraw()方法,要绘制的图案在这里实现*/

public void onDraw(Canvas canvas) {

super.onDraw(canvas);

/**画笔颜色*/

mPaint.setColor(Color.RED);

/**画笔样式*/

mPaint.setStyle(Style.FILL);

/**画笔宽度*/

mPaint.setStrokeWidth(2);

/**画矩形*/

canvas.drawRect(10, 10, 100, 100, mPaint);

mPaint.setColor(Color.BLUE);

/**设置画笔抗钜齿*/

mPaint.setAntiAlias(true);

/**绘制文字*/

canvas.drawText("画的是文字", 20, 120, mPaint);

mPaint.setColor(Color.GREEN);

/**画圆*/

canvas.drawCircle(100f, 100f, 50f, mPaint);

}

}

-------在res/values文件夹下建立attrs.xml文件,自定义我们View的属性------------------------

<?xml version="1.0" encoding="utf-8"?>

<resources>

<declare-styleable name="DefaultView">

<attr name="textColor" format="color" />

<attr name="textSize" format="dimension" />

</declare-styleable>

</resources>

----------在我们的布局文件中使用----------

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

xmlns:app="http://schemas.android.com/apk/res/com.ldm.map"<!--要加上这句话-->

android:layout_width="match_parent"

android:layout_height="match_parent" >

<com.ldm.map.DefaultView

android:layout_width="match_parent"

android:layout_height="wrap_content"

app:textColor="#f0f0f0"<!--前缀是app:-->

app:textSize="16sp" />

</LinearLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: