I think it will be better to use it as a simple reference:
<declare-styleable name="TCButton"> <attr name="customText" format="string"/> <attr name="backgroundImage" format="reference" /> </declare-styleable>
And set it in your xml like this:
<your.package.name.TCButton android:layout_width="wrap_content" android:layout_height="wrap_content" custom:customText="Some custom text" custom:backgroundImage="@drawable/myImage" />
And in your class set the attributes like this:
public TCButton(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MembershipItemView, 0, 0); String customText; Drawable backgroundImage; try { customText = a.getString(R.styleable.TCButton_customText); backgroundImage = a.getDrawable(R.styleable.TCButton_backgroundImage); } finally { a.recycle(); } if(!TextUtils.isEmpty(customText)) { ((TextView)findViewById(R.id.yourTextView)).setText(customText); } if(null != backgroundImage) { ((ImageView)findViewById(R.id.yourImageView)).setBackgroundDrawable(backgroundImage); } }
PS: Don't forget to add this line for the root element of the layout you are using your custom view in
xmlns:custom="http://schemas.android.com/apk/res-auto"
If you don't set this, you won't be able to access your custom attributes.