以前一直都是用ndroid自带的属性,突然发现自定义xml属性也是非常重要,于是总结了一下。
在values文件夹下新建的attr.xml文件,该文件为自定义属性。
//attr.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- MyView为自定义视图类 -->
<!-- 注意:自定义属性必须一个不少的添加到布局文件中,否则编译失败 -->
<declare-styleable name="MyView">
<attr name="textcolor" format="color"/>
<attr name="textsize" format="dimension"/>
</declare-styleable>
<!-- 还可以继续添加自定义视图的自定义属性 -->
<!-- 自定义属性 -->
<attr name="myviewbg" format="reference"/>
</resources>
//布局文件activity_main.xml
<!-- xmlns:android="http://schemas.android.com/apk/res/android"是调用系统的xml属性 -->
<!-- xmlns:test="http://schemas.android.com/apk/res/com.example.attrdemo" 命名为"test" 调用的是自定义属性 -->
<RelativeLayout
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:test="http://schemas.android.com/apk/res/com.example.attrdemo"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<com.example.attrdemo.MyView
android:id="@+id/myview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
test:textcolor="#98298490"
test:textsize="100sp"/>
<!--第二种引用方式 -->
<ImageView
android:layout_below="@id/myview"
android:id="@+id/imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="?attr/myviewbg"/>
</RelativeLayout>
//style.xml文件(第二种引用方式)
<pre name="code" class="html"><resources>
<style name="AppBaseTheme" parent="android:Theme.Light">
</style>
<!--一张小机器人图片 -->
<style name="AppTheme" parent="AppBaseTheme">
<item name="myviewbg">@drawable/ic_launcher</item>
</style>
</resources>
//自定义视图
<pre name="code" class="html">public class MyView extends View{
private Paint paint;
private String str="this is a attr demo!!!";
public MyView(Context context) {
super(context);
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
paint=new Paint();
TypedArray array=context.obtainStyledAttributes(attrs, R.styleable.MyView);
//如果在布局的xml文件中没有定义R.styleable.MyView_textcolor的值,则默认为“#000000”颜色值
int color=array.getColor(R.styleable.MyView_textcolor, 000000);
//如果在布局的xml文件中没有定义R.styleable.MyView_textsize的值,则默认为18dp
float size=array.getDimension(R.styleable.MyView_textsize, 18);
paint.setColor(color);
// paint.setTextSize(size);
//调用完后通常 :TypedArray 通常最后调用 .recycle()方法,为了保持以后使用该属性一致性
array.recycle();
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
canvas.drawText(str, 50, 50, paint);
}
}
猛 击 下 载