ImageView扩展:我如何广告自定义属性

时间:2014-01-10 16:25:33

标签: android android-view

如果我创建一个扩展ImageView的类,是否可以创建一个可以在XML布局中设置的自定义属性?

<com.myPackage.MyCustomImageView
    xmlns:cusimgview="http://schemas.android.com/apk/res-auto" 
    android:id ="@+id/myImageView"
    cusimgview:customattribute ="something like a color"
/>

2 个答案:

答案 0 :(得分:1)

在values文件夹中创建一个名为attrs.xml的文件。像这样添加你的自定义属性: -

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ClassNameGoesHere of your custom widget like imageview">
        <attr name="custom_width" format="dimension" />
        <attr name="custom_color" format="color" />
    </declare-styleable>
</resources>

在您自定义的ImageView类中,即扩展imageview,可以在构造函数中执行此操作: -

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.your styable name defined above, defStyle, 0);

int customColor = a.getColorStateList(R.styleable.customclassname_custom_color);

答案 1 :(得分:1)

创建一个值xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="toastText">
    <attr name="toast" format="string"/>
</declare-styleable>
</resources>
布局中的

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res/your.app.package.name"
style="@style/wrapContent"
android:orientation="vertical" android:gravity="center_horizontal">
<your.app.package.name.OwnButton
        android:id="@+id/button"
        style="@style/wrapContent"
        android:text="ABC"
        yourapp:toast="abc" />
</LinearLayout>

扩展按钮

public class OwnButton extends Button {
public OwnButton(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.toastText);
    String toastText = a.getString(R.styleable.toastText_toast);
    Toast.makeText(getContext(), toastText, Toast.LENGTH_SHORT).show();
}
}