您的位置:首页 > 移动开发 > Android开发

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可以用来给别的组件赋值,只要那个控件处理了这个值就行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: