Android自訂View需要繼承View,重寫建構函式、onDraw,(onMeasure)等函數。
如果自訂的View需要有自訂的屬性,需要在values下建立attrs.xml。在其中定義你的屬性。
在使用到自訂View的xml布局檔案中需要加入xmlns:首碼="http://schemas.android.com/apk/res/你的自訂View所在的包路徑".
在使用自訂屬性的時候,使用首碼:屬性名稱,如my:textColor="#FFFFFFF"。
[java]
package com.example.cumsview
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);
}
}
相應的屬性檔案:attrs.xmlcopy
<?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/com.example.cumsview"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<com.example.cumsview.MyView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
my:textColor="#FFFFFFFF"
my:textSize="22dp"
/>
</LinearLayout>
MainActivity.java
package com.example.cumsview;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
效果如下: