android在自定义View的xml中设置自定义的成员属性

来源:互联网 发布:江苏省软件协会 编辑:程序博客网 时间:2024/06/06 05:07

今天有个需求,是这样的:

之前写了个自定义的View,然后在layout的xml中写成如下样子:

<?xml version="1.0" encoding="utf-8"?><com.xxx.gui.map.ParamView            android:id="@+id/view_1"            android:layout_width="600dip"            android:layout_height="220dip" />

现在情况变了,又有个地方也要用到这个ParamView,一个地方要求在这个xml里设置ParamView的一个成员变量的值(如当前页currentPage)为1,另一个要求设置为2,这时该怎么做呢?

解决方法:

1.思路:要是可以在xml中直接设置自定义View里的成员变量的值就好了。没错,是这条路,但是没这么简单。具体步骤见2。

2.步骤:

    Step1:修改layout中的xml文件。先看下代码,如下:

<?xml version="1.0" encoding="utf-8"?><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:test_ns="http://schemas.android.com/apk/res/com.xxx.gui"    android:layout_width="fill_parent"    android:layout_height="fill_parent" >    <RelativeLayout        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:padding="10dip" >        <com.xxx.gui.map.ParamView            android:id="@+id/view_1"            android:layout_width="600dip"            android:layout_height="220dip"            test_ns:current_page="1" />        <com.xxx.gui.map.ParamView            android:id="@+id/view_2"            android:layout_width="600dip"            android:layout_height="160dip"            android:layout_below="@id/gsm_view_1"            android:layout_marginTop="10dip"            test_ns:current_page="2" />    </RelativeLayout></ScrollView>

说明
(1)其中修改的地方,先是添加了个命名空间,test_ns自己定义的变量名,下面两处都用到了,以test_ns:开头;
(2)再说xmlns:test_ns=http://schemas.android.com/apk/res/com.xxx.gui这句,后面的com.xxx.gui是你的项目的包名,就是你在AndroidManifest.xml中写的PackageName属性;

(3)current_page,可不是ParamView的成员变量,它与res/values下的attrs.xml中的一个变量名相对应;那就开始看Step2吧!

Step2:在res/values下创建一个attrs.xml文件,示例如下:

<?xml version="1.0" encoding="utf-8"?><resources><declare-styleable name="param_view">  <attr name="current_page" format="integer" />  </declare-styleable>  </resources>



其中,param_view、current_page,都是取个名称,方便在java文件中引用(如R.Styleable.param_view),format标签,意思是current_page这个变量的值是什么类型的,可以是integer、string、color(如0xFFFFFF)、dimension(如52dip)等等。

 

Step3:在自定义View(如ParamView.java)中做如下修改,片段代码如下:

public class ParamView extends View {private int currentPage = 1;。。。。。。// 在xml中写的自定义View,调用的是下面的构造函数public ParamView(Context context, AttributeSet attrs) {super(context, attrs);// 得到TypedArray对象TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.param_view);// 从param_view.xml中设置属性,在此得到currentPage = ta.getInt(R.styleable.param_view_current_page, 1);}。。。。。。}


说明:
(1)首先是获取TypedArray的对象,obtainStyledAttributes的两个参数,第一个不用说了,第二个,就是res/values下的attrs.xml中那个标签;

(2)param_view_current_page这个变量哪来的?它是attrs.xmlparam_viewcurrent_page标签中间加一个“_”连在一起的,写过style的都习惯这种方法;

(3)注意这里都是R.styleable.xxx,不要写成R.style.xxx;

 

以上,几天没写博客了,希望自己能坚持下去,也谢谢大家的浏览!