歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android自定義view控件

Android自定義view控件

日期:2017/3/1 9:53:59   编辑:Linux編程

在平時的開發過程中簡單的,Android自帶的view控件不能滿足我們的創意。這個時候就需要我們手動去自定義它,好讓view隨心所欲的創新。

好了直入主題:

第一步:定義一個類(myView)繼承自View,代碼如下
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 class MyViewe xtends View{
private Paintm Paint;
private Context mContext;
private static final String mString="Welcome";
public MyView(Context context){
super(context);
}
public MyView(Context context,AttributeSet attr){
super(context,attr);
}
@Override
protected void onDraw(Canvas canvas){
//TODOAuto-generatedmethodstub
super.onDraw(canvas);
mPaint=newPaint();
//設置畫筆顏色
mPaint.setColor(Color.RED);
//設置填充
mPaint.setStyle(Style.FILL);
//畫一個矩形,前倆個是矩形左上角坐標,後面倆個是右下角坐標
canvas.drawRect(newRect(10,10,100,100),mPaint);
mPaint.setColor(Color.BLUE);
//繪制文字
canvas.drawText(mString,10,110,mPaint);
}
}

第二步:將我們自定義的View加入到main.xml布局文件中,代碼如下:
<?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>

這就是簡單的一個實現過程,方法就是這樣。如果想成長,那麼你就根據這個步驟,一邊查看api,一邊動手寫自己的view。

相關閱讀: Android自定義view屬性 http://www.linuxidc.com/Linux/2013-08/88919.htm

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved