I think it is 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 install it in xml as follows:
<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 these attributes:
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: Remember to add this line to the root element of the layout that you are using in the custom view in
xmlns:custom="http://schemas.android.com/apk/res-auto"
If you do not set this, you will not be able to access your user attributes.
Ionut Negru Aug 6 '14 at 10:50 2014-08-06 10:50
source share