Android自定義View實現很簡單
繼承View,重寫構造函數、onDraw,(onMeasure)等函數。
如果自定義的View需要有自定義的屬性,需要在values下建立attrs.xml。在其中定義你的屬性。
在使用到自定義View的xml佈局文件中需要加入xmlns:前綴="http://schemas.android.com/apk/res/你的自定義View所在的包路徑".
在使用自定義屬性的時候,使用前綴:屬性名,如my:textColor="#FFFFFFF"。
實例:
package demo.view.my; 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.util.AttributeSet; import android.view.View; /** * 這個是自定義的TextView. * 至少需要重載構造方法和onDraw方法 * 對於自定義的View如果沒有自己獨特的屬性,可以直接在xml文件中使用就可以了 * 如果含有自己獨特的屬性,那麼就需要在構造函數中獲取屬性文件attrs.xml中自定義屬性的名稱 * 並根據需要設定默認值,放在在xml文件中沒有定義。 * 如果使用自定義屬性,那麼在應用xml文件中需要加上新的schemas, * 比如這裏是xmlns:my="http://schemas.android.com/apk/res/demo.view.my" * 其中xmlns後的“my”是自定義的屬性的前綴,res後的是我們自定義View所在的包 * @author Administrator * */ public class MyView extends View { Paint mPaint; //畫筆,包含了畫幾何圖形、文本等的樣式和顏色信息 public MyView(Context context) { super(context); } public MyView(Context context, AttributeSet attrs){ super(context, attrs); mPaint = new Paint(); //TypedArray是一個用來存放由context.obtainStyledAttributes獲得的屬性的數組 //在使用完成後,一定要調用recycle方法 //屬性的名稱是styleable中的名稱+“_”+屬性名稱 TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyView); int textColor = array.getColor(R.styleable.MyView_textColor, 0XFF00FF00); //提供默認值,放置未指定 float textSize = array.getDimension(R.styleable.MyView_textSize, 36); mPaint.setColor(textColor); mPaint.setTextSize(textSize); array.recycle(); //一定要調用,否則這次的設定會對下次的使用造成影響 } public void onDraw(Canvas canvas){ super.onDraw(canvas); //Canvas中含有很多畫圖的接口,利用這些接口,我們可以畫出我們想要的圖形 //mPaint = new Paint(); //mPaint.setColor(Color.RED); mPaint.setStyle(Style.FILL); //設置填充 canvas.drawRect(10, 10, 100, 100, mPaint); //繪製矩形 mPaint.setColor(Color.BLUE); canvas.drawText("我是被畫出來的", 10, 120, mPaint); } }
相應屬性文件:
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MyView"> <attr name="textColor" format="color"/> <attr name="textSize" format="dimension"/> </declare-styleable> </resources>
在佈局文件中使用:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:my="http://schemas.android.com/apk/res/demo.view.my" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <demo.view.my.MyView android:layout_width="fill_parent" android:layout_height="wrap_content" my:textColor="#FFFFFFFF" my:textSize="22dp" /> </LinearLayout>