Android expert path: Use of Custom Attributes attr. xml and TypedArray in Android
Generally, we use android: xxx =. However, sometimes we need to use custom attributes, especially for custom views.
The following steps are generally required:
1. Define an attrs. xml file under the res/values file:
2. Rewrite the constructor of our custom View. Use R. styleable. MyView to obtain our custom attributes.
TypedArray is usually used to call the. recycle () method at the end. In order to maintain future consistency with this attribute!
Package com. example. viewdemo; import android. annotation. suppressLint; import android. content. context; import android. content. res. typedArray; import android. graphics. canvas; import android. graphics. color; import android. graphics. paint; import android. graphics. paint. style; import android. graphics. rect; import android. util. attributeSet; import android. view. view; public class MyView extends View {private Paint mP Aint; private Context mContext; private static final String mString = oh, God !; Public MyView (Context context) {super (context);} public MyView (Context context, AttributeSet attrs) {super (context, attrs); mPaint = new Paint (); typedArray a = context. obtainStyledAttributes (attrs, R. styleable. myView); int textColor =. getColor (R. styleable. myView_textColor, 0 xffffff); // Add the default value float textSize =. getDimension (R. styleable. myView_textSize, 36); mPaint. setTextSize (textSize); mPaint. setColor (textColor);. recycle () ;}@ Override protected void onDraw (Canvas canvas) {super. onDraw (canvas); // you can specify whether to fill mPaint. setStyle (Style. FILL); // draw a rectangle. The first two are the coordinates in the upper left corner of the rectangle, and the last two are the coordinates in the lower right corner of the rectangle canvas. drawRect (new Rect (10, 10,100,100), mPaint); mPaint. setColor (Color. BLUE); // draw the text canvas. drawText (mString, 10,110, mPaint );}}
3. Use custom attributes in the XML layout file. Note: prefix
Running effect: