前面說過了,自定義View主要有下面三種:
1.對(duì)現(xiàn)有控件進(jìn)行擴(kuò)展
2.通過組合實(shí)現(xiàn)新的控件
3.重寫View實(shí)現(xiàn)全新控件
對(duì)現(xiàn)有控件進(jìn)行擴(kuò)展
擴(kuò)展了一個(gè)TextView,有內(nèi)外兩個(gè)矩形組成。代碼如下:
public class MyTextView extends TextView{
private Paint mPaint1,mPaint2;
public MyTextView(Context context) {
super(context);
init();
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
/**
* 初始化
*/
private void init(){
mPaint1=new Paint();
mPaint1.setColor(Color.RED);
mPaint1.setStyle(Paint.Style.FILL);
mPaint2=new Paint();
mPaint2.setColor(Color.YELLOW);
mPaint2.setStyle(Paint.Style.FILL);
}
@Override
protected void onDraw(Canvas canvas) {
//在實(shí)現(xiàn)原生控件之間,實(shí)現(xiàn)我們的邏輯
//繪制外層矩形
canvas.drawRect(0,0,getMeasuredWidth(),getMeasuredHeight(),mPaint1);
//繪制內(nèi)層矩形
canvas.drawRect(10,10,getMeasuredWidth()-10,getMeasuredHeight()-10,mPaint2);
//保存畫布狀態(tài)
canvas.save();
// 繪制文字前各平移100像素
canvas.translate(100, 100);
//父類完成的方法,繪制文字
super.onDraw(canvas);
canvas.restore();
}
}
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<com.example.ahuang.viewandgroup.View.MyTextView
android:layout_width="200dp"
android:layout_height="100dp"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:gravity="center"
android:text="擴(kuò)展的TextView"/>
</LinearLayout>
在onDraw()方法里,有個(gè) super.onDraw(canvas);調(diào)用父類的方法高镐,但是在調(diào)用之前,我們可以實(shí)現(xiàn)自己的邏輯畸冲。這里這要是畫了兩個(gè)矩形嫉髓,保存畫布,并對(duì)畫布進(jìn)行了平移邑闲,平移之后調(diào)用了父類的onDraw()方法算行。可以看到苫耸,即便是我們?cè)诓季治募镉玫搅薬ndroid:gravity="center"屬性州邢,android:text="擴(kuò)展的TextView"屬性還是平移了。
通過組合實(shí)現(xiàn)新的控件
創(chuàng)建組合控件褪子,通常需要繼承一個(gè)合適的ViewGroup量淌,我們一般要給它指定一些可配置的屬性,讓它變得更具擴(kuò)展性嫌褪。例如呀枢,很多app都有跟下圖類似的TopBar控件,我們完全可以自己定義一個(gè)類似的TopBar控件笼痛。
1.定義屬性,在res的Values目錄下創(chuàng)建一個(gè)attrs.xml的屬性定義文件裙秋。主要是為TopBar提供可自定義的屬性。
<resources>
<declare-styleable name="TopBar">
<!--中間title的自定義屬性-->
<attr name="mTitle" format="string"></attr>
<attr name="mTitleSize" format="dimension"></attr>
<attr name="mTitleColor" format="color"></attr>
<!--左邊圖片的自發(fā)定義屬性-->
<attr name="mLeftBackGround" format="reference"></attr>
<!--右邊TextView的自定義屬性-->
<attr name="rightTitle" format="string"></attr>
<attr name="rightTitleSize" format="dimension"></attr>
<attr name="rightTextColor" format="color"></attr>
</declare-styleable>
</resources>
我們定義了控件名字,字體顏色残吩,背景3個(gè)屬性,format是值該屬性的取值類型:
一共有:string,color,demension,integer,enum,reference,float,boolean,fraction,flag;
reference:參考某一資源ID倘核,color:顏色值泣侮,boolean:布爾值,dimension:尺寸值紧唱,float:浮點(diǎn)值
integer:整型值活尊,string:字符串,fraction:百分?jǐn)?shù)漏益, enum:枚舉值蛹锰, flag:位或運(yùn)算
2.自定義TopBar,獲取自定義的屬性绰疤。
public class TopBar extends RelativeLayout {
//控件
private ImageView img_left;
private TextView tv_title;
private TextView tv_right;
// 布局屬性铜犬,用來控制組件元素在ViewGroup中的位置
private LayoutParams mLeftParams, mTitlepParams, mRightParams;
// 左控件的屬性值,即我們?cè)赼tts.xml文件中定義的屬性
private Drawable mBackGround; //左側(cè)圖片的背景圖
//中間title的屬性值
private float mTitleTextSize;
private int mTitleTextColor;
private String mTitle;
//右邊TextView的屬性值
private int mRightTextColor;
private float mRightTextSize;
private String mRightText;
public TopBar(Context context) {
this(context, null);
}
public TopBar(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TopBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//設(shè)置背景色
setBackgroundColor(0xFF190D31);
//獲得atts.xml定義的屬性值轻庆,存儲(chǔ)在TypedArray中
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TopBar);
//左側(cè)圖片
mBackGround = ta.getDrawable(R.styleable.TopBar_mLeftBackGround);
//中間title
mTitleTextSize = ta.getDimension(R.styleable.TopBar_mTitleSize, 10);
mTitleTextColor = ta.getColor(R.styleable.TopBar_mTitleColor, 0);
mTitle = ta.getString(R.styleable.TopBar_mTitle);
//右邊Title
mRightTextColor = ta.getColor(R.styleable.TopBar_rightTextColor, 0);
mRightTextSize = ta.getDimension(R.styleable.TopBar_rightTitleSize, 1);
mRightText = ta.getString(R.styleable.TopBar_rightTitle);
// 獲取完TypedArray的值后癣猾,一般要調(diào)用
// recyle方法來避免重新創(chuàng)建的時(shí)候的錯(cuò)誤
ta.recycle();
//創(chuàng)建控件
img_left=new ImageView(context);
tv_title=new TextView(context);
tv_right=new TextView(context);
// 為創(chuàng)建的組件元素賦值
img_left.setBackground(mBackGround);
tv_title.setText(mTitle);
tv_title.setTextColor(mTitleTextColor);
tv_title.setTextSize(mTitleTextSize);
tv_right.setText(mRightText);
tv_right.setTextColor(mRightTextColor);
tv_right.setTextSize(mRightTextSize);
//設(shè)置組件的位置
mLeftParams=new LayoutParams(60, 60);
mLeftParams.addRule(ALIGN_PARENT_LEFT,TRUE);
mLeftParams.addRule(CENTER_VERTICAL,TRUE);
addView(img_left,mLeftParams);
mTitlepParams=new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
mTitlepParams.addRule(CENTER_IN_PARENT,TRUE);
addView(tv_title,mTitlepParams);
mRightParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
mRightParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, TRUE);
mRightParams.addRule(RelativeLayout.CENTER_VERTICAL, TRUE);
addView(tv_right, mRightParams);
}
3.在布局文件里引用我們自定義的TopBar
需要注意的是,在Android Studio中余爆,第三方控件都使用如下代碼來引入名字空間
xmlns:custom="http://schemas.android.com/apk/res-auto" 將引入的第三方控件的名字空間取為custom纷宇,之后在xml文件中使用自定義的屬性時(shí),就可以通過這個(gè)名字空間來引用蛾方。
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<com.example.ahuang.viewandgroup.View.TopBar
android:layout_width="match_parent"
android:layout_height="45dp"
custom:mLeftBackGround="@mipmap/back_icon"
custom:mTitle="購物車"
custom:mTitleColor="@android:color/white"
custom:mTitleSize="5sp"
custom:rightTextColor="@android:color/white"
custom:rightTitle="編輯"
custom:rightTitleSize="5sp"/>
</LinearLayout>
4.雖然我們定義了需要的TopBar像捶,但是它是還不能響應(yīng)點(diǎn)擊事件的,現(xiàn)在桩砰,我們讓自定義的TopBar響應(yīng)點(diǎn)擊事件拓春。修改代碼如下:
在TopBar里加入回調(diào)接口,分別定義了左右控件的點(diǎn)擊回調(diào)時(shí)間
//定義接口五芝,響應(yīng)點(diǎn)擊事件
public interface topbarClickListener {
//左按鈕點(diǎn)擊事件
void leftClick();
//右按鈕點(diǎn)擊事件
void rightClick();
}
定義回調(diào)接口痘儡,并暴露給調(diào)用者。
// 映射傳入的接口對(duì)象
private topbarClickListener mListener;
// 暴露一個(gè)方法給調(diào)用者來注冊(cè)接口回調(diào)
public void setOnTopbarClickListener(topbarClickListener mListener) {
this.mListener = mListener;
}
對(duì)控件設(shè)置回調(diào)事件
img_left.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mListener.leftClick();
}
});
tv_right.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mListener.rightClick();
}
});
在Activity里實(shí)現(xiàn)回調(diào)枢步,實(shí)現(xiàn)控件的點(diǎn)擊監(jiān)聽沉删。
mTopBar.setOnTopbarClickListener(new TopBar.topbarClickListener() {
@Override
public void leftClick() {
Toast.makeText(CustomViewActivity.this, "click left", Toast.LENGTH_SHORT)
.show();
}
@Override
public void rightClick() {
Toast.makeText(CustomViewActivity.this, "click right", Toast.LENGTH_SHORT)
.show();
}
});
最后,要說明一點(diǎn)的是醉途,TopBar一般在很多頁面頂部引用矾瑰,為了方便,我們可以放在一個(gè)頭布局里面隘擎,然后再用到的地方通過include引用殴穴。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="45dp">
<com.example.ahuang.viewandgroup.View.TopBar
android:id="@+id/topBar"
android:layout_width="match_parent"
android:layout_height="45dp"
custom:mLeftBackGround="@mipmap/back_icon"
custom:mTitle="購物車"
custom:mTitleColor="@android:color/white"
custom:mTitleSize="5sp"
custom:rightTextColor="@android:color/white"
custom:rightTitle="編輯"
custom:rightTitleSize="5sp"/>
</LinearLayout>
在用到的地方,通過
<include layout="@layout/head_layout"></include>
添加控件。
重寫View實(shí)現(xiàn)全新控件
如下圖所示的圖片采幌,在很多音樂播放器上會(huì)有劲够,但是android里沒有現(xiàn)成的控件,所以可以自定義一個(gè)類似的控件休傍。相信大家可以很快找到思路征绎,也就是繪制一個(gè)個(gè)矩形,每個(gè)矩形之間稍微偏移一點(diǎn)距離即可磨取。
1.初始化操作
private void init() {
mPaint = new Paint();
mPaint.setColor(Color.GREEN);
mPaint.setStyle(Paint.Style.FILL);
mRectCount = 12;
}
2.主繪制方法
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (int i = 0; i < mRectCount; i++) {
mRandom = Math.random();
canvas.drawRect(mRectWidth * i + offset, (float) (mRectHeight * mRandom), mRectWidth * (i+1),
mRectHeight, mPaint);
}
postInvalidateDelayed(300);
}
3.為了達(dá)到一個(gè)更好的效果程拭,增加一個(gè)LinearGradient漸變效果
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = getWidth();
mRectWidth = mWidth / mRectCount; //音頻條的寬度
mRectHeight = getHeight(); //音頻條的高度叉弦,要乘上一個(gè)隨機(jī)數(shù)
mLinearGradient=new LinearGradient(0,0,mRectWidth,mRectHeight,
Color.BLUE,Color.GREEN, Shader.TileMode.CLAMP);
mPaint.setShader(mLinearGradient);
}
所有代碼如下:
public class AudioBar extends View {
private Paint mPaint; //定義畫筆
private int mWidth; //屏幕的寬度
private int mRectWidth; //音頻條的寬度
private int mRectHeight; //音頻條的高度
private int mRectCount; //音頻條的個(gè)數(shù)
private int offset = 5; //音頻條的偏移量
private double mRandom; //隨機(jī)數(shù)
private LinearGradient mLinearGradient;
public AudioBar(Context context) {
this(context, null);
}
public AudioBar(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public AudioBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setColor(Color.GREEN);
mPaint.setStyle(Paint.Style.FILL);
mRectCount = 12;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = getWidth();
mRectWidth = mWidth / mRectCount; //音頻條的寬度
mRectHeight = getHeight(); //音頻條的高度最爬,要乘上一個(gè)隨機(jī)數(shù)
mLinearGradient=new LinearGradient(0,0,mRectWidth,mRectHeight,
Color.BLUE,Color.GREEN, Shader.TileMode.CLAMP);
mPaint.setShader(mLinearGradient);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (int i = 0; i < mRectCount; i++) {
mRandom = Math.random();
canvas.drawRect(mRectWidth * i + offset, (float) (mRectHeight * mRandom), mRectWidth * (i+1),
mRectHeight, mPaint);
}
postInvalidateDelayed(300);
}
}