一、自定義組合控制元件(通用標題欄)
自定義組合控制元件就是將多個控制元件組合成為一個新的控制元件,主要解決多次重復使用同一型別的布局,如我們頂部的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系列之詳解繪制流程
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/248623.html
標籤:其他
上一篇:Kotlin:FlowLayout橫向流式自定義布局
下一篇:Flutter 申請權限問
