Android开发之attrs.xml

来源:互联网 发布:ubuntu root password 编辑:程序博客网 时间:2024/05/17 09:25

首先在res/valus文件目录下新建attrs.xml文件,用来定义新增的属性

<?xml version="1.0" encoding="utf-8"?><resources>    <declare-styleable name="MyView">        <attr name="textSize" format="dimension"></attr>        <attr name="textColor" format="color"></attr>    </declare-styleable></resources>
format是这个值的属于什么类型dimension是属于尺寸,color则是属于颜色


新建TestView.class继承View(这里可以继承任何控件,布局等)

public class TestView extends View{Paint mPaint = null;public TestView(Context context) {super(context);// TODO Auto-generated constructor stub}public TestView(Context context, AttributeSet attrs) {super(context, attrs);init(context, attrs);}public TestView(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);init(context, attrs);}public void init(Context context, AttributeSet attrs){TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyView);   //获取自定义属性,MyView是自定义属性的名称                                                                                             //可以自己随便定义什么名称int color = ta.getColor(R.styleable.MyView_textColor, 0x00000000);   //获取自定义属性文件中的某个自定义属性float size = ta.getDimension(R.styleable.MyView_textSize, 28);  //同上mPaint = new Paint();mPaint.setColor(color);mPaint.setTextSize(size);ta.recycle();   //据说是为了保存获取的自定义值}@Overridepublic void draw(Canvas canvas) {canvas.drawText("哈哈", 60, 60, mPaint);super.draw(canvas);}}
在布局文件中使用:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:test="http://schemas.android.com/apk/res-auto" //xmlns:test="http://schemas.android.com/apk/res/com.huaqiang.testattrs"    android:layout_width="fill_parent"                   //com.huaqiang.testattrs这是你AndroidManifest.xml文件中的Package路径    android:layout_height="fill_parent"                  //可以用res-auto来代替,这个会自动寻找    android:orientation="vertical" >        <com.huaqiang.effect.TestView        android:id="@+id/text"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        test:textSize="@dimen/big"        test:textColor="@color/red"/></LinearLayout>

这个就能用自己自定义的属性了

0 0
原创粉丝点击