【问题标题】:ImageView extended: how can i ad a custom attributeImageView 扩展:如何添加自定义属性
【发布时间】:2014-01-10 16:25:33
【问题描述】:

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

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

【问题讨论】:

标签: android android-view


【解决方案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);

【讨论】:

    【解决方案2】:

    创建一个值 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();
    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-24
      • 1970-01-01
      • 2018-02-26
      • 1970-01-01
      • 2011-05-23
      • 2018-09-17
      相关资源
      最近更新 更多