前言
今天看了Google上关于View的教程,看的真是云里雾里。虽然篇幅很长,看完一遍实在不想再看第二遍,不过自己还是坚持看完了第二遍,第三遍,第四遍。。。后面几遍越看越熟练,我看着Google示例APP里面的代码,然后参考着Google教程里面的讲解,慢慢的和教程里面的一个个点对上号。到写这篇博客为止,我还是没有很好的把其中的原理融会贯通,但是还是想先记录一下目前从代码里学习到的知识,以后看到好的View代码再多练习。
比如自定义XML属性我都不是很熟悉,在这里只是熟悉它的大概流程,里真正学会还差很远。
正文
首先我们来看看效果图(动态图不会弄。。见谅):
我们可以用手指拖动这个圆盘开始旋转,然后过一段时间它会慢慢停下来,并且旋转过程中左边对应的饼图部分的文字一直在变化。
下面我就按照如何自己写出一个自定义View的过程来记录学到的东西:
定义一个View子类
自定义当然离不开自己创建一个类继承View,不过我们可以选择继承基础类view,也可以是基础类之上的类(如Button),如果UI复杂想在自定义View里继续嵌套子元素,还可以继承ViewGroup。比如在PieChart里面,是这么写的:
public class PieChart extends ViewGroup {
定义自定义样式
每一个View都有自己的样式,比如说我们在XML里面经常使用的 android:layout_width = “match_parent”,如果我们自己定制View,我们还可以自己定义自己的样式,习惯上来讲,我们把自定义view的自定义属性放在res/values/attrs.xml文件里面。我们需要在< resource >元素下面定义一个子元素 < declare-styleable >,然后写上这个样式的名字,一般和自定义View类的名字一样。在这个< declare-styleable >里面来定义有需求的属性,在pieChart里面是这样的:
<declare-styleable name="PieChart">
<attr name="autoCenterPointerInSlice" format="boolean"/>
<attr name="highlightStrength" format="float"/>
<attr name="labelColor" format="color"/>
<attr name="labelHeight" format="dimension"/>
<attr name="labelPosition" format="enum">
<enum name="left" value="0"/>
<enum name="right" value="1"/>
</attr>
<attr name="labelWidth" format="dimension"/>
<attr name="labelY" format="dimension"/>
<attr name="pieRotation" format="integer"/>
<attr name="pointerRadius" format="dimension"/>
<attr name="showText" format="boolean"/>
</declare-styleable>
然后我们应该在XML文件里面应用这个样式,不过我们应该重新加入一个新的命名空间,比如之前我们用android:layout_weight,android:centerInParent之类的属性,其实都是因为先引入了xmlns:android=”http://schemas.android.com/apk/res/android”,”http://schemas.android.com/apk/res/android“是具体的URI,用指令xmlns可以指定一个别名还代替这一长串的URI,我们这里引入xmlns:custom=”http://schemas.android.com/apk/res/com.example.custom_view”,这样,我们就能用custom:XX=YY这样的自定义属性了。
注意:引入自己的命名空间,规则是在res后面加入APP的具体包名。这里的包名是com.example.custom_view。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/com.example.custom_view"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height=