1)自定义控件时自定义属性:
在Eclipse中,首先在/res/values下创建一个attrs.xml文件来定义此属性集,其中写入你要自定义属性的名称和格式:
代码实例:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="myAttrs">
<attr name="radioButtonDrawable" format="string" />
<attr name="radioButtonText" format="string" />
<attr name="radioButtonNoReadMessage" format="integer" />
</declare-styleable>
</resources>
如上代码实例,其中 name 表示此属性集的名称.
创建自定义布局的.java文件后。在XML文件中要使用自定义布局的自定义属性时,只需声明在XML文件中一个命名空间即可。
代码实例:
<LinearLayout xmlns:android="
http://schemas.android.com/apk/res/android"
xmlns:myAppAttr="
http://schemas.android.com/apk/res/com.example.myApp"
xmlns:tools="
http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
如上代码中的: xmlns:myAppAttr=”
http://schemas.android.com/apk/res/com.example.myApp”其中最后为自己的项目包名。xmlns后面为自定义属性名称可以随意写
在此XML中使用自定义属性的代码:
<com.example.myApp.view.SettingViewItem
android:id="@+id/sv_update"
android:layout_width="match_parent"
android:layout_height="wrap_content"
myAppAttr:desc_on="自动更新已关闭"
myAppAttr:desc_off="自动更新已开启"
myAppAttr:title="自动更新设置" />12345671234567
如上代码中的使用自定义属性时,前面的命名空间即是在XML头部声明的。
最后在自定义属性的.java文件中获取此自定义属性的信息,通过命名空间的URL即可:
public SettingViewItem(Context context, AttributeSet attrs) {
super(context, attrs);
private static final String NAMESPACE="
http://schemas.android.com/apk/res/com.example.myApp";
String mTitle = attrs.getAttributeValue(NAMESPACE,"title");
String mDesc_on = attrs.getAttributeValue(NAMESPACE,"desc_on");
String mDesc_off = attrs.getAttributeValue(NAMESPACE,"desc_off");
}
如上代码在Eclipse中没任何问题,但在AndroidStudio中在XML中声明命名空间时则会报如下错误。
In Gradle projects, the actual package used in the final APK can
vary; for example,you can add a .debug package suffix in one version and
not the other. Therefore, you should not hardcode the application
package in the resource; instead, use the special namespace
http://schemas.android.com/apk/res-auto which will cause the tools to figure out the right namespace for the
resource regardless of the actual package used during the build.
修改:
将XML头部的命名空间修改为如下:
<LinearLayout xmlns:android="
http://schemas.android.com/apk/res/android"
xmlns:weichatAttr="
http://schemas.android.com/apk/res-auto"
xmlns:tools="
http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
如报错信息所示:use the special namespace
http://schemas.android.com/apk/res-auto .故命名空间将不能先Eclipse中所示的那样写了。
在.java文件中获取自定义属性的内容:
public SettingViewItem(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.myAttrs);
String mTitle = typedArray.getString(R.styleable.myAttrs_title);
String mDesc_on = attrs.getAttributeValue(R.styleable.myAttrs_desc_on);
String mDesc_off = attrs.getAttributeValue(R.styleable.myAttrs_desc_off);
typedArray.recycle();
}1234567812345678
在获取属性信息时,用到”R.styleable.myAttrs_title”,很显然,他在每个属性前面都加了”myAttrs_”。而myAttrs是在attrs.xml文件中定义的属性集名称。
本回答被网友采纳