Android custom View (1)

Source: Internet
Author: User

Android custom View (1)

Smile on life, can penetrate the fog; smile on life, can stick to the end; smile on life, can resolve crisis; smile on life, can light up the darkness.

 

Description: Custom View (which can be used multiple times in the layout file)

 

1. steps:

1. Custom View attributes

2. Obtain custom attributes in the View constructor.

3. Override onMesure (optional, which generally needs to be rewritten. If there is no write, it is provided by the system by default)

4. Override onDraw

Note:

Step 2: We have rewritten three constructor methods. The default layout file calls the constructor of two parameters, so remember to let all constructor call the constructor of our three parameters. We can get custom attributes in the constructor of the three parameters.

Step 3: the height and width measured by the system are MATCH_PARNET, so we cannot set the measurement height and width without rewriting. When we set it to WRAP_CONTENT, it will also be displayed as MATCH_PARNET.

SpecMode of MeasureSpec. There are three types:
EXACTLY: usually set a clear value or MATCH_PARENT
AT_MOST: indicates that the sub-layout is limited to a maximum value, which is generally WARP_CONTENT.
UNSPECIFIED: indicates the size of the sub-layout, which is rarely used.

 

 

 

Example:

The layout file res/layout/activity_main.xml is as follows:

 

     
  
 
Be sure to introduce xmlns: custom = "http://schemas.android.com/apk/res/com.example.customview01" to our namespace, the package path behind it refers to the package of the project

 

 

The following is the res/values/attrs. xml file: (define our attributes and declare our entire style .)

 

 
                 
                              
  
 
We have defined three attributes: font, font color, and font size. format is the value type:
Common types: string, color, demension, integer, enum, reference, float, boolean, fraction, flag


The custom mmtitleview. java file is as follows:

 

 

Public class CustomTitleView extends View {// text private String mTitleText; // text color private int mTitleTextColor; // text size private int mTitleTextSize; // control the range of text painting during painting: private Rect mBound; private Paint mPaint; public CustomTitleView (Context context) {this (context, null);} public CustomTitleView (Context context, attributeSet attrs) {this (context, attrs, 0);} // obtain the custom style attribute public CustomTitleView (Context context, AttributeSet attrs, int defStyle) {super (context, attrs, defStyle); // obtain the custom style attribute TypedArray a = context. getTheme (). obtainStyledAttributes (attrs, R. styleable. customTitleView, defStyle, 0); int n =. getIndexCount (); for (int I = 0; I <n; I ++) {int attr =. getIndex (I); switch (attr) {case R. styleable. customTitleView_titleText: mTitleText =. getString (attr); break; case R. styleable. customTitleView_titleTextColor: // The default color is black mTitleTextColor =. getColor (attr, Color. BLACK); break; case R. styleable. customTitleView_titleTextSize: // The default value is 16sp. TypeValue can also convert sp to pxmTitleTextSize =. getDimensionPixelSize (attr, (int) TypedValue. applyDimension (TypedValue. COMPLEX_UNIT_SP, 16, getResources (). getDisplayMetrics (); break;}. recycle (); // get the width and height of the drawn text mPaint = new Paint (); mPaint. setTextSize (mTitleTextSize); // mPaint. setColor (mTitleTextColor); mBound = new Rect (); mPaint. getTextBounds (mTitleText, 0, mTitleText. length (), mBound); // this custom View has no advantage over TextView, so add an event for the custom View: this. setOnClickListener (new OnClickListener () {public void onClick (View arg0) {mTitleText = randomText (); postInvalidate () ;}});} private String randomText () {Random random = new Random (); Set
 
  
Set = new HashSet
  
   
(); While (set. size () <4) {int randomInt = random. nextInt (10); set. add (randomInt);} StringBuffer sb = new StringBuffer (); for (Integer I: set) {sb. append ("" + I);} return sb. toString ();} protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {// super. onMeasure (widthMeasureSpec, heightMeasureSpec); int width = 0; int height = 0; // set the width of int specMode = MeasureSpec. getMode (widthMeasureSpec); int specSize = MeasureSpec. getSize (widthMeasureSpec); switch (specMode) {case MeasureSpec. EXACTLY: // specify width = getPaddingLeft () + getPaddingRight () + specSize; break; case MeasureSpec. AT_MOST: // usually WARP_CONTENTwidth = getPaddingLeft () + getPaddingRight () + mBound. width (); break;} // set the height specMode = MeasureSpec. getMode (heightMeasureSpec); specSize = MeasureSpec. getSize (heightMeasureSpec); switch (specMode) {case MeasureSpec. EXACTLY: // specify height = getPaddingTop () + getPaddingBottom () + specSize; break; case MeasureSpec. AT_MOST: // usually WARP_CONTENTheight = getPaddingTop () + getPaddingBottom () + mBound. height (); break;} setMeasuredDimension (width, height);} protected void onDraw (Canvas canvas) {mPaint. setColor (Color. YELLOW); canvas. drawRect (0, 0, getMeasuredWidth (), getMeasuredHeight (), mPaint); mPaint. setColor (mTitleTextColor); canvas. drawText (mTitleText, getWidth ()/2-mBound. width ()/2, getHeight ()/2 + mBound. height ()/2, mPaint );}}
  
 

 

We added a click event to randomly generate a four-digit random number each time. we can add a noise in onDraw and rewrite it to the Verification code.

 

The main interface file MainActivity. java is as follows:

 

public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}}

Take your time and enjoy it

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.