自定义视图(自定义属性)

前言


  前两篇我们介绍了下自定义视图到一些方法,自定义视图(继承View) 和  自定义视图(组合控件)  ,有了自定义控件有时候在灵活应用到方面还有所欠缺,因此需要进行一些自定义属性。

属性定义


  我们先把所需要到属性定义好,在res/values/目录下新建xml文件attrs.xml,此文件定义了所有需要到属性,为了说明这个过程就定义了一个attr_title属性。如下所示

  attrs.xml

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

2 <resources>  

3     <declare-styleable name="CombinView">  

4         <attr name="attr_title" format="string"></attr>

5     </declare-styleable>  

6 </resources>  

其中:format属性可以用的值包括以下内容

reference:参考某一资源ID

color:颜色值

boolean:布尔值

dimension:尺寸值

float:浮点值

integer:整型值

string:字符串

fraction:百分数

enum:枚举值

flag:位或运算

以上内容可以单独使用,也可以组合使用,比如reference|color,中间用“|”隔开

属性应用

  属性定义好了,下面就看怎么使用了,如下所示

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

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

 3     xmlns:cview="http://schemas.android.com/apk/res/com.example.testcview"

 4     android:layout_width="match_parent"

 5     android:layout_height="match_parent"

 6     tools:context="${packageName}.${activityClass}" 

 7     

 8     >

 9 

10     <com.example.testcview.CombinView

11         android:id="@+id/combinView1"

12         android:layout_width="wrap_content"

13         android:layout_height="wrap_content"

14         android:layout_alignParentRight="true"

15         android:layout_alignParentTop="true" 

16         cview:attr_title="自定义题头"

17         >

18     </com.example.testcview.CombinView>

19 

20 </RelativeLayout>

  其中有两点需要注意,

  1>xmlns:cview="http://schemas.android.com/apk/res/com.example.testcview",需要声明自己的命名空间,前面的部分为http://schemas.android.com/apk/res/,此部分为固定,后一部分为自己的应用的包名com.example.testcview

  2>在自定义控件上设置自定义属性,cview:attr_title="自定义题头",需要增加自己的命名控件,

这样自定义属性就应用到自定义控件上了。

Java代码获取及设置属性内容

  在自定义控件的构造函数中获取设置的值并设置到相应位置,如下所示

 

 1 public class CombinView extends RelativeLayout {

 2 

 3     public CombinView(Context context, AttributeSet attrs) {

 4         super(context, attrs);

 5         LayoutInflater inflater = (LayoutInflater)context.getSystemService    (Context.LAYOUT_INFLATER_SERVICE);

 6         RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.custom_view,this);

 7         

 8         //获取自定义属性  

 9         TypedArray tArray = context.obtainStyledAttributes(attrs, R.styleable.CombinView);  

10         String title = tArray.getString(R.styleable.CombinView_attr_title);

11         

12         TextView tvTitle = (TextView) layout.findViewById(R.id.tvTitle);

13         System.out.println("title="+title);

14         tvTitle.setText(title);

15         

16         tArray.recycle();

17     }

18 

19 }

 

其中,通过TypedArray tArray = context.obtainStyledAttributes(attrs, R.styleable.CombinView); 这句来获取自定义属性内容,然后通过

String title = tArray.getString(R.styleable.CombinView_attr_title);获取指定属性的值

这样,我们就把自定义属性的值取下来了,具体怎么使用就看具体需求就可以了

 

后记

  通过这篇和前两篇的文章,自定义控件的大体流程就差不多了,差的只是在这个架子上増枝添叶,其原理是一样的。

原文地址:http://www.cnblogs.com/luoaz/p/3985039.html

你可能感兴趣的:(自定义)