以launcher为例说明自定义控件的属性:
1、 在layout里面定义控件,如:
<com.android.launcher.Workspace
android:id="@+id/workspace"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
launcher:defaultScreen="1">
<include android:id="@+id/cell1" layout="@layout/workspace_screen" />
<include android:id="@+id/cell2" layout="@layout/workspace_screen" />
<include android:id="@+id/cell3" layout="@layout/workspace_screen" />
</com.android.launcher.Workspace>
2、 该控件workspace下面有一个属性是defaultScreen,这属性不是ViewGroup(workspace类是继承于ViewGroup)所定义的属性,那么我们可以在/res/values里面的attrs.xml里面定义
具体的定义方法如下:
<resources>
<declare-styleable name="Workspace">
<attr name="defaultScreen" format="integer" />
</declare-styleable>
</resources>
3、 这样我们在Workspace的类里面就可以去除在layout里面对该属性的赋值,方法如下:
Int mDefaultScreen;
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Workspace, defStyle, 0);
mDefaultScreen = a.getInt(R.styleable.Workspace_defaultScreen, 1);
a.recycle();
本文以Launcher中的Workspace控件为例,详细介绍了如何在Android中自定义控件属性,包括在XML布局文件中声明控件及属性、在attrs.xml文件中定义属性格式,以及在Java代码中获取这些属性值的方法。
4478

被折叠的 条评论
为什么被折叠?



