android自定义view要怎么使用

如题所述

1. 初始化
这个其实就是构造函数啦,在这里你可以为这个 view 设置特定的属性啊!那么如何自定义属性呢?首先你得在 res -->
values 这个目录下新建 attrs 的资源文件!在这个文件中配置你要的自定义属性!先看一下代码
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="WeekSelectView">
<attr name="selectColor" format="color"></attr>
<attr name="unSelectColor" format="color"></attr>
<attr name="lineColor" format="color"></attr>
<attr name="textColor" format="color"></attr>
<attr name="textSize" format="dimension"></attr>
<attr name="selectSize" format="dimension"></attr>
<attr name="lineWidth" format="dimension"></attr>
<attr name="lineHeight" format="dimension"></attr>
<attr name="space" format="dimension"></attr>
</declare-styleable>
</resources>

其中的 declare-styleable 标签就是添加自定义属性用的,里面包含的每一个 attr 就代表每一个自定义属性!后天面的 format 属性代表每一个属性的类型!接着就是我该如何使用它们呢!我们只要在布局文件中使用代码就行了:
<com.kidbot.library.widget.weekselect.WeekSelectView
xmlns:weekselect="http://schemas.android.com/apk/res-auto"
android:id="@+id/weekselect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
weekselect:lineHeight="10dp"
weekselect:lineWidth="50dp"
weekselect:selectSize="10dp"
weekselect:space="30dp"
weekselect:textSize="15sp" />

要注意的是如果要在布局文件中使用这些自定义属性得加这句话: xmlns:weekselect="http://schemas.android.com/apk/res-auto" 其中 weekselect 这个字段属于用户自定义!
好了知道如何使用了,那么在写自定义 view 的时候,我们该怎么获取这些这些值呢?
TypedArray typedArray=context.obtainStyledAttributes(attrs, R.styleable.WeekSelectView);
selectColor=typedArray.getColor(R.styleable.WeekSelectView_selectColor, Defalut_Select_Color);
unSelectColor=typedArray.getColor(R.styleable.WeekSelectView_unSelectColor, Defalut_UnSelect_Color);
lineColor=typedArray.getColor(R.styleable.WeekSelectView_lineColor, Defalut_Line_Color);
textSize = typedArray.getDimension(R.styleable.WeekSelectView_textSize, Defalut_Text_Size);
textColor = typedArray.getColor(R.styleable.WeekSelectView_textColor, Defalut_Text_Color);
selectSize = typedArray.getDimension(R.styleable.WeekSelectView_selectSize, Defalut_Select_Size);
lineHeight = typedArray.getDimension(R.styleable.WeekSelectView_lineHeight, Defalut_Line_Height);
lineWidth=typedArray.getDimension(R.styleable.WeekSelectView_lineWidth, Defalut_Line_Width);
space=typedArray.getDimension(R.styleable.WeekSelectView_space,Defalut_Space);
typedArray.recycle();

代码比较简单,我就不详细说了,唯一要注意的就是不要忘了释放这个资源。
温馨提示:内容为网友见解,仅供参考
第1个回答  2018-07-30
视图,凡事能被用户看到的小控件都是一种view,也可以自定义view本回答被网友采纳
相似回答