Hello, everyone. Our tutorial today is to customize View Learning in the Android tutorial, for beginners, they are accustomed to the traditional Android page layout, the following code:
<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/ Res/android " android:orientation=" vertical " android:layout_width=" Fill_parent " android:layout_height= "Fill_parent" > <TextView android:layout_width= " Fill_parent " android:layout_height=" Wrap_content " android:text=" @string/hello " /> </LinearLayout>
Of course, the above layout can help us to complete the development of simple applications, but if you want to write a complex application, so it is a bit far-fetched, we do not believe that the source can be studied to see, master writing layout, such as the above layout master is usually written like this:
<?xml version= "1.0" encoding= "Utf-8"?> <A> <B></B> </A>
Where a extends Linerlayout, B extends TextView.
To help make it easier for everyone to understand, I wrote a simple Demo with the following steps:
Start by creating a new Android project named Viewdemo .
Then customize a view class named MyView (extends View) . The code is as follows:
PackageCom.android.tutor; ImportAndroid.content.Context; ImportAndroid.graphics.Canvas; ImportAndroid.graphics.Color; ImportAndroid.graphics.Paint; ImportAndroid.graphics.Rect; ImportAndroid.graphics.Paint.Style; ImportAndroid.util.AttributeSet; ImportAndroid.view.View; Public classMyViewextendsView {PrivatePaint Mpaint; PrivateContext Mcontext; Private Static FinalString mstring = "Welcome to Mr Wei ' s Blog"; PublicMyView (Context context) {Super(context); } PublicMyView (Context context,attributeset attr) {Super(CONTEXT,ATTR); } @Overrideprotected voidOnDraw (canvas canvas) {//TODO auto-generated Method Stub Super. OnDraw (canvas); Mpaint=NewPaint (); //Set Brush ColorMpaint.setcolor (color.red); //Set the FillMpaint.setstyle (Style.fill); //draw a rectangle, the first two are the coordinates of the upper left corner of the rectangle, the next two are the lower right corner coordinatesCanvas.drawrect (NewRect (10, 10, 100, 100), mpaint); Mpaint.setcolor (Color.Blue); //Draw TextCanvas.drawtext (mstring, 10, 110, Mpaint); } }
Then add our custom View to the main.xml layout file with the following code:
<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/ Res/android " android:orientation=" vertical " android:layout_width=" Fill_parent " android:layout_height= "Fill_parent" > <TextView android:layout_width= " Fill_parent " android:layout_height=" Wrap_content " android:text=" @string/hello " /> <com.android.tutor.MyView android:layout_width= "Fill_parent" Android:layout_height= "fill_parent" /> </LinearLayout>
Finally, the effect is as follows:
Android Master Advanced Tutorial (iii)----app for customizing view in Android.