您的位置:首页 > 其它

自定义View添加自定义属性详细

2015-03-23 11:14 351 查看
自定义view经常需要设置一些属性, 很多人应该都知道,属性都是写在res/values文件夹下一个自定义的文件夹,但是通常很多人都起名attrs,

看下他的写法

<?xml version="1.0" encoding="utf-8"?>

<resources>

<declare-styleable name="MyView">

<attr name="textColor" format="color"></attr>

<attr name="textSize" format="dimension"></attr>

<attr name="background" format="reference"></attr>

<attr name="text" format="string"></attr>

</declare-styleable>

<declare-styleable name="rotateTextView">

<attr name="rotate" format="integer"></attr>

</declare-styleable>

</resources>

这是我写的一个自定义TextView 跟一个旋转了一定角度的TextView添加的属性;

很多人在使用这个的时候都是在自定义的view中通过

TypedArray array =context.obtainStyledAttributes(attrs, R.styleable.MyView);

int color =array.getColor(R.styleable.MyView_textColor, 0XFF00FF00);

float textSize =array.getDimension(R.styleable.MyView_textSize, 22);

float degressSize =attrs.getAttributeFloatValue("http://www.ywlx.net/apk/res/easymobi", "rotate", 0);

这样的方式获取到这个属性来进行设置,然后绘制,在layout中也可以,但是我在第一次弄的时 候就是不行,然后就查了点东西:

如果要在layout中使用的话,那么你必须要给相应的自定义view添加相应的命名空间,如果不添加时不会认识你的熟悉的,也就不能再布局中设置:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical" >

<com.example.myview.RotateTextView

xmlns:myview="http://schemas.android.com/apk/res/com.example.myview"

android:id="@+id/rotateTextView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textSize="20sp"

android:text="fgfghghghg"

myview:rotate="50"

android:background="@drawable/ic_launcher"

></com.example.myview.RotateTextView>

<!-- <com.example.myview.MTextView

android:id="@+id/text"

android:layout_width="wrap_content"

android:layout_height="40dp"

android:text="qweqweqweq"

android:textColor="#000000"

></com.example.myview.MTextView> -->

<!-- <com.example.myview.MyListView

android:id="@+id/listView"

android:layout_width="match_parent"

android:layout_height="match_parent"



></com.example.myview.MyListView> -->

</LinearLayout>

命名空间的规则就是使用你当前包的包名xmlns:myview="http://schemas.android.com/apk/res/com.example.myview"

这个是用来定义命名空间用的,myview代表的命名空间

com.example.myview表示该命名空间用于哪个包

然后你就可以使用你定义的属性;

自定义view学习中。

一个自定义的倾斜textView:http://download.csdn.net/detail/u012808234/8524853
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: