前面說過了,自定義View主要有下面三種:
1.對現(xiàn)有控件進行擴展
2.通過組合實現(xiàn)新的控件
3.重寫View實現(xiàn)全新控件
對現(xiàn)有控件進行擴展
擴展了一個TextView,有內(nèi)外兩個矩形組成。代碼如下:
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) {
//在實現(xiàn)原生控件之間,實現(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="擴展的TextView"/>
</LinearLayout>
在onDraw()方法里,有個 super.onDraw(canvas);調(diào)用父類的方法,但是在調(diào)用之前,我們可以實現(xiàn)自己的邏輯。這里這要是畫了兩個矩形,保存畫布,并對畫布進行了平移,平移之后調(diào)用了父類的onDraw()方法。可以看到,即便是我們在布局文件里用到了android:gravity="center"屬性,android:text="擴展的TextView"屬性還是平移了。
通過組合實現(xiàn)新的控件
創(chuàng)建組合控件,通常需要繼承一個合適的ViewGroup,我們一般要給它指定一些可配置的屬性,讓它變得更具擴展性。例如,很多app都有跟下圖類似的TopBar控件,我們完全可以自己定義一個類似的TopBar控件。
1.定義屬性,在res的Values目錄下創(chuàng)建一個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個屬性,format是值該屬性的取值類型:
一共有:string,color,demension,integer,enum,reference,float,boolean,fraction,flag;
reference:參考某一資源ID,color:顏色值,boolean:布爾值,dimension:尺寸值,float:浮點值
integer:整型值,string:字符串,fraction:百分數(shù), enum:枚舉值, flag:位或運算
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;
// 左控件的屬性值,即我們在atts.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定義的屬性值,存儲在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)建的時候的錯誤
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文件中使用自定義的屬性時,就可以通過這個名字空間來引用。
<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)點擊事件的,現(xiàn)在,我們讓自定義的TopBar響應(yīng)點擊事件。修改代碼如下:
在TopBar里加入回調(diào)接口,分別定義了左右控件的點擊回調(diào)時間
//定義接口,響應(yīng)點擊事件
public interface topbarClickListener {
//左按鈕點擊事件
void leftClick();
//右按鈕點擊事件
void rightClick();
}
定義回調(diào)接口,并暴露給調(diào)用者。
// 映射傳入的接口對象
private topbarClickListener mListener;
// 暴露一個方法給調(diào)用者來注冊接口回調(diào)
public void setOnTopbarClickListener(topbarClickListener mListener) {
this.mListener = mListener;
}
對控件設(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里實現(xiàn)回調(diào),實現(xià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();
}
});
最后,要說明一點的是,TopBar一般在很多頁面頂部引用,為了方便,我們可以放在一個頭布局里面,然后再用到的地方通過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實現(xiàn)全新控件
如下圖所示的圖片,在很多音樂播放器上會有,但是android里沒有現(xià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.為了達到一個更好的效果,增加一個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(); //音頻條的高度,要乘上一個隨機數(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; //音頻條的個數(shù)
private int offset = 5; //音頻條的偏移量
private double mRandom; //隨機數(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(); //音頻條的高度,要乘上一個隨機數(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);
}
}