2

If I create a class that extends ImageView is it possible to create a custom attribute that can be set in the XML layout like this?

<com.myPackage.MyCustomImageView
    xmlns:cusimgview="http://schemas.android.com/apk/res-auto" 
    android:id ="@+id/myImageView"
    cusimgview:customattribute ="something like a color"
/>
hichris123
  • 10,145
  • 15
  • 56
  • 70
erik
  • 4,946
  • 13
  • 70
  • 120

2 Answers2

1

Create a file called attrs.xml in values folder. Add your custom properties in it like this :-

<?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>

in your custom ImageView class which is extending imageview lets say, do this in its constructor :-

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

int customColor = a.getColorStateList(R.styleable.customclassname_custom_color);
Rahul Gupta
  • 5,275
  • 8
  • 35
  • 66
1

Create a value xml

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

in the layout

<?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>

extend button

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();
}
}