‘sup developers. Today we are going to create a custom view class that will add certain fuctionality in our application.
In magento, to express a field to be required, magento by default add a ‘*’ in front of it.
Like
To add this functionality, normally we write some boring code. Why can we do like this:
1 2 3 4 5 |
android:isRequired="true" or myTextView.isRequired(true); |
and we get the same functionality
Yes, this possible. Here comes our CUSTOM VIEWS
What we have to do in order to create custom view.
Step1. Declare a styleable and add attribute that we want to show in our xml (custom view)
1 2 3 4 5 6 7 8 |
<?xml version="1.0" encoding="utf-8"?> <resources> <!--attribute set--> <declare-styleable name="RequiredTextView"> <!--attribute name--> <attr name="isRequired" format="boolean"></attr> </declare-styleable> </resources> |
Step 2. Create Custom View Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
public class RequiredTextView extends TextView { private boolean isRequired; public RequiredTextView(Context context) { super(context); } public RequiredTextView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.RequiredTextView, 0, 0); Log.d("DEBUG", "a.length()"+a.length()); try { isRequired = a.getBoolean(R.styleable.RequiredTextView_isRequired, false); Log.d("DEBUG", "isRequired" + isRequired); } finally { a.recycle(); } changeToIsRequired(); } public RequiredTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.RequiredTextView, 0, 0); try { isRequired = a.getBoolean(R.styleable.RequiredTextView_isRequired, false); Log.d("DEBUG", "isRequired" + isRequired); } finally { a.recycle(); } changeToIsRequired(); } private void changeToIsRequired() { //get the attributes specified in attrs.xml using the name we included if (isRequired) { this.setText(this.getText() + "*"); invalidate(); } } protected void onDraw(Canvas canvas) { super.onDraw(canvas); } } |
Step3. Access custom view in Layout XML.
1 2 3 4 5 6 7 |
<com.mobikul.mobikulbaselibrary.RequiredTextView xmlns:requiredTextView="http://schemas.android.com/apk/res-auto" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Subject" android:textAppearance="?android:attr/textAppearanceMedium" requiredTextView:isRequired="true" /> |
Note: Don’t forget to use namespace. For gradle project use this:
1 |
xmlns:myNs="http://schemas.android.com/apk/res-auto" |
Custom Views plays an important role. They not only makes the work easier but they SAVE OUR LIFEs.
That’s all folk’s Stay tuned!!!