一、自定義組合控件(通用标題欄)
自定義組合控件就是将多個控件組合成為一個新的控件,主要解決多次重複使用同一類型的布局。如我們頂部的HeaderView以及dailog等,我們都可以把他們組合成一個新的控件。通常是繼承一個系統現有的ViewGroup(LinearLayout...)
1.編寫通用标題欄的布局檔案:左邊是傳回按鈕、中間是文字标題、右邊可能是文本可能是圖示
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/header_root_layout"
android:layout_width="match_parent"
android:layout_height="48dp">
<ImageView
android:id="@+id/backIv"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginStart="10dp"
android:src="@mipmap/icon_title_back_2" />
<TextView
android:id="@+id/titleTv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="标題"
android:textColor="#000000"
android:textSize="18dp" />
<TextView
android:id="@+id/rightTv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_marginEnd="10dp"
android:text="完成"
android:textColor="#f0000000"
android:textSize="16dp"
android:visibility="gone" />
<ImageView
android:id="@+id/rightIv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_marginEnd="10dp"
android:src="@mipmap/icon_setting" />
</RelativeLayout>
2.自定義View的java代碼:CommonTitleBarLayout.java
public class CommonTitleBarLayout extends LinearLayout {
private TextView titleTv, rightTv;
private ImageView backIv, rightIv;
private RelativeLayout rootLayout;
public CommonTitleBarLayout(Context context) {
this(context, null);
}
public CommonTitleBarLayout(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public CommonTitleBarLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView(context);
initAttrs(context, attrs);
}
/**
* @param context 上下文文本
*/
private void initView(Context context) {
LayoutInflater.from(context).inflate(R.layout.layout_common_title_bar, this, true);
titleTv = findViewById(R.id.titleTv);
rightTv = findViewById(R.id.rightTv);
backIv = findViewById(R.id.backIv);
rightIv = findViewById(R.id.rightIv);
rootLayout = findViewById(R.id.header_root_layout);
}
/**
* @param context 上下文文本
* @param attrs 如果需要自定義屬性,可以從attrs參數擷取屬性值
*/
private void initAttrs(Context context, AttributeSet attrs) {
//擷取自定義的各個屬性值
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CommonTitleBarLayout);
String title = typedArray.getString(R.styleable.CommonTitleBarLayout_titleText);//擷取format="string"
int titleColor = typedArray.getColor(R.styleable.CommonTitleBarLayout_titleTextColor, 0x000000);//擷取format="color"
int titleSize = (int) typedArray.getDimension(R.styleable.CommonTitleBarLayout_titleTextSize, 18f);//擷取format="dimension"
int backgroundColor = typedArray.getColor(R.styleable.CommonTitleBarLayout_backgroundColor, 0xFFFFFF);//擷取format="color"
int type = typedArray.getInt(R.styleable.CommonTitleBarLayout_rightShowImgOrText, 0);//擷取枚舉類型值
if (type == 1) {//右邊按鈕顯示圖檔icon
rightTv.setVisibility(GONE);
rightIv.setVisibility(VISIBLE);
int rightIcon = typedArray.getResourceId(R.styleable.CommonTitleBarLayout_rightIcon, R.drawable.ic_launcher_background);//擷取format="reference"
} else if (type == 2) {//右邊按鈕顯示文本
rightTv.setVisibility(VISIBLE);
rightIv.setVisibility(GONE);
String rightText = typedArray.getString(R.styleable.CommonTitleBarLayout_rightText);//擷取format="string"
int rightColor = typedArray.getColor(R.styleable.CommonTitleBarLayout_rightTextColor, 0x000000);//擷取format="color"
int rightSize = (int) typedArray.getDimension(R.styleable.CommonTitleBarLayout_rightTextSize, 16f);//擷取format="dimension"
} else {//都不顯示
rightTv.setVisibility(GONE);
rightIv.setVisibility(GONE);
}
Log.i("AttributeSet", "title=" + title + "titleColor=" + titleColor + "type=" + type + "titleSize" + titleSize);
}
//以下這些方法:對外提供設定的接口,可以看自己需求補充
public void setLeftListener(OnClickListener onClickListener) {
if (onClickListener != null) {
backIv.setOnClickListener(onClickListener);
}
}
public void setRightListener(OnClickListener onClickListener) {
if (onClickListener != null) {
rightTv.setOnClickListener(onClickListener);
}
}
public void setTitle(String title) {
titleTv.setText(title);
}
public void setTitleColor(@ColorInt int color) {
titleTv.setTextColor(color);
}
public void setRightBtnText(String text) {
rightTv.setText(text);
}
public void setRightBtnColor(@ColorInt int color) {
rightTv.setTextColor(color);
}
public void setBackgroundColor(int color) {
rootLayout.setBackgroundColor(color);
}
}
3.自定義屬性
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CommonTitleBarLayout">
<!--中間标題文本-->
<attr name="titleText" format="string"/>
<!--中間标題文本顔色-->
<attr name="titleTextColor" format="color"/>
<!--中間标題文本大小-->
<attr name="titleTextSize" format="dimension"/>
<!--右邊文本-->
<attr name="rightText" format="string"/>
<!--右邊文本顔色-->
<attr name="rightTextColor" format="color"/>
<!--右邊文本大小-->
<attr name="rightTextSize" format="dimension"/>
<!--标題欄背景色-->
<attr name="backgroundColor" format="color"/>
<!--右邊按鈕是顯示TextView還是ImageView-->
<attr name="rightShowImgOrText">
<enum name="showImageView" value="1"/>
<enum name="showTextView" value="2"/>
<enum name="allNotShow" value="0"/>
</attr>
<!--右邊圖檔icon-->
<attr name="rightIcon" format="reference"/>
</declare-styleable>
</resources>
4.使用
<?xml version="1.0" encoding="utf-8"?>
<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="match_parent"
android:orientation="vertical">
<com.example.testproject.CommonTitleBarLayout
android:id="@+id/title_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
custom:backgroundColor="#FFFFFF"
custom:rightShowImgOrText="showTextView"
custom:rightText="設定"
custom:rightTextColor="#000000"
custom:rightTextSize="16dp"
custom:titleText="今日新聞"
custom:titleTextColor="#000000"
custom:titleTextSize="18dp" />
</LinearLayout>
public class TestActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CommonTitleBarLayout titleBarLayout = findViewById(R.id.title_bar);
titleBarLayout.setTitle("2121212");
titleBarLayout.setLeftListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
以上就是實作一個自定義組合控件的代碼:可以發現我們通過了兩種方式來控制标題欄的内容和樣式:1、自定義屬性;2、對外提供相關設定接口(二者選其一或者都選,因為xml是布局的時候配置的,比較固定;提供java接口可以靈活進行設定)
二、繼承系統控件(如:拓展TextView功能)
繼承系統的控件可以分為繼承View子類(如TextVIew等)和繼承ViewGroup子類(如LinearLayout等),根據業務需求的不同,實作的方式也會有比較大的差異。這裡介紹一個比較簡單的,繼承自View的實作方式。
業務需求:為文字中間添加一條橫線。
因為這種實作方式會複用系統的邏輯,大多數情況下我們希望複用系統的
onMeaseur
和
onLayout
流程,是以我們隻需要重寫
onDraw
方法 ,實作非常簡單
/**
* Created by BinKang on 2021/1/12.
* Des :文本中間劃橫線
*/
public class LineTextView extends TextView {
private Paint mPaint;
public LineTextView(Context context) {
super(context);
init();
}
public LineTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public LineTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
//構造方法中初始化工作
private void init() {
mPaint = new Paint();
mPaint.setColor(Color.RED);
}
//重寫draw方法,繪制我們需要的中間線
//這裡我們隻需要重寫onDraw方法就行,一些onMeasure方法已經在父類TextView做好了,不需要我們去管,和平常使用TextView正常使用就行
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
//繪制中心曲線,起點坐标(0,height/2),終點坐标(width,height/2)
canvas.drawLine(0, height / 2, width, height / 2, mPaint);
}
}
使用:
<com.example.testproject.LineTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="這段話沒用了" />
效果:
三、直接繼承View
直接繼承View會比上一種實作方複雜一些,這種方法的使用情景下,完全沒有複用系統控件的邏輯,除了要重寫
onDraw
外還需要對
onMeasure
方法進行重寫。
我們用自定義View來繪制一個圓形。
public class RoundView extends View {
private Paint mPaint;
public RoundView(Context context) {
super(context);
init();
}
public RoundView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public RoundView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setColor(Color.RED);
mPaint.setAntiAlias(true);//去掉邊緣鋸齒狀
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);//View的内部有實作預設的onMeasure方法,但在View的源碼當中并沒有對AT_MOST和EXACTLY兩個模式做出區分,也就是說View在wrap_content和match_parent兩個模式下是完全相同的,都會是match_parent,顯然這與我們平時用的View不同,是以我們要重寫onMeasure方法
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
//處理wrap_contentde情況
if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(300, 300);
} else if (widthMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(300, heightSize);
} else if (heightMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(widthSize, 300);
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//擷取各個邊距的padding值
int paddingLeft = getPaddingLeft();
int paddingRight = getPaddingRight();
int paddingTop = getPaddingTop();
int paddingBottom = getPaddingBottom();
//擷取繪制的View的寬度
int width = getWidth() - paddingLeft - paddingRight;
//擷取繪制的View的高度
int height = getHeight() - paddingTop - paddingBottom;
//繪制View,左上角坐标(0+paddingLeft,0+paddingTop),右下角坐标(width+paddingLeft,height+paddingTop)
canvas.drawRoundRect(0 + paddingLeft, 0 + paddingTop, width + paddingLeft, height + paddingTop, width / 2, width / 2, mPaint);
}
}
注意:
1、我們實作的onMeasure()方法:super.onMeasure(widthMeasureSpec, heightMeasureSpec);是使用了系統View的測量算法,我們下面複習了setMeasureDimension()方法,是以這個super是沒有的,可以注釋掉;為什麼不用系統的呢?下面跟進去看看系統的實作:
可以看到:在View的源碼當中并沒有對
AT_MOST
和
EXACTLY
兩個模式做出區分,也就是說View在
wrap_content
和
match_parent
兩個模式下是完全相同的,都會是
match_parent。是以要重寫onMeasure()。
四、繼承ViewGroup
自定義ViewGroup的過程相對最複雜一些,因為除了要對自身的大小和位置進行測量之外,還需要對子View的測量參數負責。相關執行個體在上一篇文章詳細講解了,實戰FlowLayout簡易的流式布局。
Android自定義View系列之詳解繪制流程