android 自定义View并在xml中控制

来源:互联网 发布:讲故事什么软件好 编辑:程序博客网 时间:2024/06/06 08:25

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">第一篇学习笔记,就随便记录点。</span>

新建一个类,继承View

复写2种构造方法

复写onDraw方法

在自定义View里面完成实现目标后,分类封装(绘图、逻辑)


在res文件夹的values中新建attrsd的xml文件

新建样式

<pre name="code" class="html"><declare-styleable name="example">      <attr name="example1" format="integer"/>      <attr name="example2" format="boolean"/></declare-styleable>
</pre><pre name="code" class="html">
在布局文件中,引入命名空间
<pre name="code" class="html">xmlns:xx="http://schemas.android.com/apk/res/com.example.xmltest"
(xx是随便自己起的,最后res/接包名)
在自定义控件中引用
xx:example1="30"
xx:example2="false"
最后在自定义View里面解析
在有2个参数的构造方法中,创建TypedArray对象
<pre name="code" class="java">TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.example);
int data = ta.getInt(R.styleable.example_example1,0); //后面的0是一个默认值参数
boolean data1 = ta.getBoolean(R.styleable.example_example2, false);
这样,就可以直接在布局xml中印象代码中的参数了。

0 0
原创粉丝点击