Android自定义组件(2)
2013-08-18 23:06
363 查看
<com.example.selectortest.CustomView android:layout_width="wrap_content" android:layout_height="wrap_content"> </com.example.selectortest.CustomView>
可以发现,我们使用CustomView组件的时候,只是简单的指明了它的宽度和高度。
现在,假设有这么一个需要,在之前的矩形组件里面显示指定条数的直线。这样,就需要我们自定义属性了。
就像在写程序时,使用一个类型之前需要先定义这个类型一样。我们需要先在res/values/attrs.xml中定义这种类型。
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="CustomView2"> <attr name="line_numbers" format="integer"></attr> </declare-styleable> </resources>这样,我们就可以在xml中指定line_numbers等于多少了。
显然,直线是由Draw函数画出来的,我们需要在CustomView类里面来解析xml,得到直线条数,然后画出直线。
package com.example.selectortest; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Rect; import android.util.AttributeSet; import android.view.View; public class CustomView extends View { private Paint mPaint = null; private String mString = "Programmer"; private int nLines = 0; public CustomView(Context context, AttributeSet attrs) { super(context, attrs); //解析xml,得到直线条数。 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView2); nLines = a.getInteger(R.styleable.CustomView2_line_numbers, 1); } @Override public void draw(Canvas canvas) { // TODO Auto-generated method stub super.draw(canvas); mPaint = new Paint(); mPaint.setColor(Color.BLUE); mPaint.setStyle(Style.STROKE); canvas.drawRect(new Rect(10 ,10 ,100 ,100), mPaint); mPaint.setColor(Color.GREEN); mPaint.setTextSize(35.0f); canvas.drawText(mString, 10, 60, mPaint); //画直线 for(int i = 1 ; i <= nLines ;i ++) { canvas.drawLine(0, i*10, 200, i*10, mPaint); } } }使用方法:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:custom_namespace="http://schemas.android.com/apk/res/com.example.selectortest" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <com.example.selectortest.CustomView android:layout_width="wrap_content" android:layout_height="wrap_content" custom_namespace:line_numbers="3"> </com.example.selectortest.CustomView> </LinearLayout>看看效果:
这里,有一点值得提一下,Style CustomerView2(包含line_numbers属性)与CustomerView类是没有关系的,也就是说,Stype CustomerView2可以用来给别的组件赋值,只要那个控件处理了这个值就行。
相关文章推荐
- h5开发之cordova/phonegap自定义组件调用android native代码
- Android组件之自定义ContentProvider
- 新书内容连载(1):自定义Android组件之带图像的TextView
- android自定义组件之TopMenu
- android构建自定义的视图组件
- Android复合自定义组件(几个基本组件组成的自定义组件)
- Android自定义组件系列【14】——Android5.0按钮波纹效果实现
- 编写自定义的 Android Preference 组件
- android---(样式、主题、自定义组件)
- Android利用Canvas和Paint实现画图和自定义布局组件
- 第三部分:Android 应用程序接口指南---第二节:UI---第十二章 自定义组件
- 自定义Android View组件——实现雷达图效果
- Android中自定义组件及自定义属性
- Android 自定义view组件
- Android自定义组件03
- AndroidUI开源组件库BottomView 第三方自定义UI控件
- Android 的自定义Spinner组件实现方式
- Android自定义组件之自动换行ViewGroup
- Android自定义组件系列【9】——Canvas绘制折线图
- Android开发——构建自定义组件