相信大家在做應(yīng)用的時(shí)候經(jīng)常會(huì)遇到顯示標(biāo)簽的情況,例如(“上班族,天枰座”這樣的),若干個(gè)標(biāo)簽長(zhǎng)短不一,每個(gè)標(biāo)簽之間還有一定的間隙,并且一行顯示不下之后,下一個(gè)標(biāo)簽顯示就需要換行,本篇文章就自定義一個(gè)View,來(lái)實(shí)現(xiàn)所說(shuō)的這個(gè)效果。
首先我們先來(lái)看看實(shí)現(xiàn)以后是什么樣的:
通過這個(gè)實(shí)際的實(shí)現(xiàn)效果我們可以做出下面的分析:
1.每個(gè)item的寬度不同
2.行/列之間有間隔
3.數(shù)據(jù)和布局進(jìn)行分離,并且布局可以自定義,于是我們考慮利用android的adapter的特性進(jìn)行實(shí)現(xiàn)
4.有自動(dòng)換行的功能
這個(gè)View大概要實(shí)現(xiàn)上面的效果,下面就開始擼碼:
先建立好這個(gè)View,繼承自ViewGroup:
public class TagView extends ViewGroup {
}
為了讓其使用更加靈活,我們自定義幾個(gè)屬性:
<declare-styleable name="TagView">
<attr name="maxLine" format="integer" />//最多允許多少行,超過的就不進(jìn)行顯示了
<attr name="itemSpace" format="dimension" />//每個(gè)item之間的寬度(每行的高度,也可以多定義一個(gè)高度)
<attr name="gravity" format="enum">////子View擺放時(shí)貼著父布局上邊還是下邊
<enum name="top" value="1" />
<enum name="bottom" value="2" />
</attr>
</declare-styleable>
定義好了以后,我們就可以在XML文件里畫布局了:
<com.test.xiao.TagView
android:id="@+id/gv_tag"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="@id/iv_photo"
android:layout_alignParentLeft="true"
android:layout_below="@id/tv_content"
android:layout_toLeftOf="@id/iv_photo"
app:gravity="bottom"http://貼著下邊進(jìn)行擺放
app:itemSpace="3dp"
app:maxLine="2" />
item的布局如下:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tv_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/shape_main_tag_sub"http://橙色的背景
android:ellipsize="end"
android:gravity="center"
android:maxLines="1"
android:paddingBottom="1dp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:paddingTop="1dp"
android:text="TextView01"
android:textColor="@color/white"
android:textSize="@dimen/ss_small_textSize" />
好了,這些準(zhǔn)備工作完成以后,我們就可以開始實(shí)現(xiàn)View的功能了,首先定義好相關(guān)變量并進(jìn)行初始化:
public class TagView extends ViewGroup {
private int itemSpace = 0;//item之間的間距
private Adapter mAdapter;//獲取數(shù)據(jù)和子item的適配器,這個(gè)adapter就是android原生提供的adapter
private int ORIENTATION;//方向值,可以取VERTICAL,HORIZONTAL(項(xiàng)目中暫時(shí)未用到垂直需求,所以暫時(shí)不需要)
private SparseArray<SparseArray<View>> views;//用于記錄第幾行,第幾個(gè)item
private SparseArray<Integer> maxHeights;//記錄每行的最大高度
private int maxLine;//設(shè)置最大的行數(shù)
private int gravity;//子View貼著上邊還是下邊(默認(rèn)上邊),1是上邊,2是下邊
public TagView(Context context) {
super(context);
init(null);
}
public TagView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public TagView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs);
}
private void init(AttributeSet attributeSet) {
views = new SparseArray<>();
maxHeights = new SparseArray();
if (attributeSet == null) {
itemSpace = Utils.dp2px(getContext(), 5);
maxLine = 10;// 默認(rèn)最大行數(shù)
} else {
TypedArray array = getContext().obtainStyledAttributes(attributeSet, R.styleable.TagView);
itemSpace = array.getDimensionPixelSize(R.styleable.TagView_itemSpace, Utils.dp2px(getContext(), 10));
gravity = array.getInt(R.styleable.TagView_gravity, 1);
maxLine = array.getInt(R.styleable.TagView_maxLine, 10);
array.recycle();
}
}
}
接下來(lái)我們需要在onMeasure里通過adapter獲取到相關(guān)的view,并且測(cè)量出每個(gè)view的寬度和高度,根據(jù)寬度來(lái)計(jì)算出我們需要多少行,每行分別需要列來(lái)放這些item:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int needWidth = MeasureSpec.getSize(widthMeasureSpec);
int needHeihgt = MeasureSpec.getSize(heightMeasureSpec);
int parentWidthMeasureSpec = MeasureSpec.makeMeasureSpec(needWidth, MeasureSpec.getMode(widthMeasureSpec));
int parentHeightMeasureSpec = MeasureSpec.makeMeasureSpec(needHeihgt, MeasureSpec.getMode(heightMeasureSpec));
if (mAdapter != null && mAdapter.getCount() > 0) {//如果adapter沒有數(shù)據(jù),則不進(jìn)行繪制,直接調(diào)用super.onMeasure
View child = null;//從adaper中獲取的子View
int childWidth = 0;//子View的寬度
int currentLineWidth = 0;//當(dāng)前行的總寬度
int currentLine = 0;//當(dāng)前是第幾行
int currentElement = 0;//當(dāng)前行的第幾個(gè)元素
int maxHeight = 0;//當(dāng)前行的最大高度
int resultHeihgt = 0;//通過子View的測(cè)量情況最終算出來(lái)的父View高度
boolean isMaxLine = false;//當(dāng)前是否已經(jīng)到達(dá)最大行
for (int i = 0; i < mAdapter.getCount(); i++) {//通過adapter來(lái)遍歷測(cè)量所有的子View
if (currentLine == maxLine) {//到達(dá)最大行數(shù)時(shí),如果還有下一行,我們就不進(jìn)行顯示了
isMaxLine = true;
break;
}
child = mAdapter.getView(i, null, this);
measureChild(child, parentWidthMeasureSpec, parentHeightMeasureSpec);//獲取子控件大小
childWidth = child.getMeasuredWidth();
if (currentLineWidth == 0) {//已經(jīng)到達(dá)新的一行
views.put(currentLine, new SparseArray<>());//新建一個(gè)用來(lái)存放新的一行元素的集合
}
if (childWidth + itemSpace + currentLineWidth > needWidth) {//需要換行
resultHeihgt += maxHeight + itemSpace;
maxHeights.put(currentLine, maxHeight);
currentLine++;
currentLineWidth = 0;
currentElement = 0;
i--;
} else {
if (child.getMeasuredHeight() > maxHeight) {
maxHeight = child.getMeasuredHeight();//計(jì)算本行的最大高度,在layout時(shí),每行的高度就以最大高度為準(zhǔn)
}
views.get(currentLine).put(currentElement, child);//在測(cè)量完了,并且分析好這個(gè)元素的位置后,將其放入集合中,待之后onLayout時(shí)進(jìn)行擺放
currentElement++;
currentLineWidth += itemSpace + childWidth;
}
}
if (resultHeihgt == 0) {//當(dāng)前item僅有一行
resultHeihgt = maxHeight;
maxHeights.put(0, maxHeight);
} else {//當(dāng)前item不止一行,且未到達(dá)最大行數(shù)限制,到這里時(shí),需要補(bǔ)齊最后一行的高度數(shù)據(jù)
if (!isMaxLine) {
resultHeihgt += maxHeight;//
maxHeights.put(currentLine, maxHeight);
}
}
setMeasuredDimension(needWidth, resultHeihgt);//設(shè)置最終的寬高
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
通過onMeasure,我們通過每個(gè)item的寬高計(jì)算出了TagView的寬高,要顯示的行數(shù),每行的高度以及每行的元素及其所處的位置(存放到了views中),通過這些得到的內(nèi)容,接下來(lái)我們就要在onLayout中計(jì)算出每個(gè)item應(yīng)該擺放的具體位置了:
//在這個(gè)方法里我們要確定每個(gè)View擺放的位置
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (mAdapter != null && mAdapter.getCount() > 0) {
View view;//當(dāng)前要進(jìn)行擺放的子View
View lastView;//當(dāng)前擺放的子View左邊的View
int childLeft, childRight, childTop, childBottom;
for (int i = 0; i < views.size() && i < maxLine; i++) {//這個(gè)循環(huán)用來(lái)循環(huán)行數(shù)
for (int j = 0; j < views.get(i).size(); j++) {//這個(gè)循環(huán)用來(lái)循環(huán)每行的列數(shù)
view = views.get(i).get(j);//第i行第j個(gè)元素
childLeft = 0;
for (int k = 0; k < j; k++) {//通過前面所有View的寬度相加,得到當(dāng)前子View的left位置
lastView = views.get(i).get(k);
childLeft += lastView.getMeasuredWidth() + itemSpace;
}
childRight = childLeft + view.getMeasuredWidth();
//確定子View上下的位置,根據(jù)gravity的不同(1是靠近父View頂部擺放,2是靠近父View底部擺放)
if (gravity == 1) {
childTop = 0;
for (int k = 0; k < i; k++) {//通過前面所有高度行數(shù)相加,得到最終的上邊位置
childTop += maxHeights.get(k) + itemSpace;
}
} else {
childTop = b - t;//b-t為最后一行的底部
for (int k = views.size() - 1 - i; k >= 0; k--) {//第一行的top位置是從最底部算起,后面所有行的高度+自身的高度值+行與行之間的空隙
childTop -= (maxHeights.get(k) + itemSpace);
}
childTop += itemSpace;//這里要加上多減去的空間
}
childBottom = childTop + view.getMeasuredHeight();
view.layout(childLeft, childTop, childRight, childBottom);
addView(view);
}
}
}
}
對(duì)于adapter,我們要給出一個(gè)可以進(jìn)行設(shè)置的方法:
public void setAdapter(Adapter adapter) {
mAdapter = adapter;
invalidate();
}
使用的時(shí)候,我們這樣使用(采用的是效果圖中的數(shù)據(jù)):
String[] testTags = new String[]{"ssssss", "大家得人生", "ssdsjdj", "我們和小李都有", "放下一切", "大大大大大大多多"};
public void onCreate(Bundle saveInstanceStates){
...
TagView gv_tag = findViewById(R.layout.gv_tag);
gv_tag.setAdapter(new ArrayAdapter<>(context, R.layout.item_main_grid_sub_tag, R.id.tv_item, data.getTags()));//采用adapter方式比較靈活
...
}
完整代碼如下:
/**
* Created by LiXiaoSong on 2017/7/10.
* 自定義Tagview,用于顯示流布局
*/
public class TagView extends ViewGroup {
private int itemSpace = 0;//item之間的間距
private Adapter mAdapter;//這里傳入的adapter僅僅使用了其簡(jiǎn)單的功能
private int ORIENTATION;//方向值,可以取VERTICAL,HORIZONTAL(項(xiàng)目中暫時(shí)未用到垂直需求,所以暫時(shí)不需要)
private SparseArray<SparseArray<View>> views;//用于記錄第幾行,第幾個(gè)item
private SparseArray<Integer> maxHeights;//記錄每行的最大高度
private int maxLine;//設(shè)置最大的行數(shù)
private int gravity;//子View貼著上邊還是下邊(默認(rèn)上邊),1是上邊,2是下邊
public TagView(Context context) {
super(context);
init(null);
}
public TagView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public TagView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs);
}
private void init(AttributeSet attributeSet) {
views = new SparseArray<>();
maxHeights = new SparseArray();
if (attributeSet == null) {
itemSpace = Utils.dp2px(getContext(), 5);
maxLine = 10;// 默認(rèn)最大行數(shù)
} else {
TypedArray array = getContext().obtainStyledAttributes(attributeSet, R.styleable.TagView);
itemSpace = array.getDimensionPixelSize(R.styleable.TagView_itemSpace, Utils.dp2px(getContext(), 10));
gravity = array.getInt(R.styleable.TagView_gravity, 1);
maxLine = array.getInt(R.styleable.TagView_maxLine, 10);
array.recycle();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int needWidth = MeasureSpec.getSize(widthMeasureSpec);
int needHeihgt = MeasureSpec.getSize(heightMeasureSpec);
int parentWidthMeasureSpec = MeasureSpec.makeMeasureSpec(needWidth, MeasureSpec.getMode(widthMeasureSpec));
int parentHeightMeasureSpec = MeasureSpec.makeMeasureSpec(needHeihgt, MeasureSpec.getMode(heightMeasureSpec));
if (mAdapter != null && mAdapter.getCount() > 0) {
View child = null;
int childWidth = 0;
int currentLineWidth = 0;
int currentLine = 0;//當(dāng)前行數(shù)
int currentElement = 0;
int maxHeight = 0;//當(dāng)前行數(shù)最大高度
int resultHeihgt = 0;
boolean isMaxLine = false;
for (int i = 0; i < mAdapter.getCount(); i++) {//這里用來(lái)存放子View的元素
if (currentLine == maxLine) {
isMaxLine = true;
break;
}
child = mAdapter.getView(i, null, this);
measureChild(child, parentWidthMeasureSpec, parentHeightMeasureSpec);//獲取子控件大小
childWidth = child.getMeasuredWidth();
if (currentLineWidth == 0) {//新的一行
views.put(currentLine, new SparseArray<>());
}
if (childWidth + itemSpace + currentLineWidth > needWidth) {//需要換行
resultHeihgt += maxHeight + itemSpace;
maxHeights.put(currentLine, maxHeight);
currentLine++;
currentLineWidth = 0;
currentElement = 0;
i--;
} else {
if (child.getMeasuredHeight() > maxHeight) {
maxHeight = child.getMeasuredHeight();
}
views.get(currentLine).put(currentElement, child);
currentElement++;
currentLineWidth += itemSpace + childWidth;
}
}
if (resultHeihgt == 0) {//當(dāng)前item僅有一行
resultHeihgt = maxHeight;
maxHeights.put(0, maxHeight);
} else {//如果不是,補(bǔ)齊最后一行的數(shù)據(jù)
if (!isMaxLine) {
resultHeihgt += maxHeight;//
maxHeights.put(currentLine, maxHeight);
}
}
setMeasuredDimension(needWidth, resultHeihgt);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (mAdapter != null && mAdapter.getCount() > 0) {
View view;
View lastView;//它前面的View
int childLeft, childRight, childTop, childBottom;
for (int i = 0; i < views.size() && i < maxLine; i++) {
for (int j = 0; j < views.get(i).size(); j++) {
view = views.get(i).get(j);//第i行第j個(gè)元素
childLeft = 0;
for (int k = 0; k < j; k++) {//通過前面所有View的寬度相加,得到最終的左邊位置
lastView = views.get(i).get(k);
childLeft += lastView.getMeasuredWidth() + itemSpace;
}
childRight = childLeft + view.getMeasuredWidth();
childTop = 0;
if (gravity == 1) {
for (int k = 0; k < i; k++) {//通過前面所有高度行數(shù)相加,得到最終的上邊位置
childTop += maxHeights.get(k) + itemSpace;
}
} else {
childTop = b - t;//設(shè)置一個(gè)底部
for (int k = views.size() - 1 - i; k >= 0; k--) {//通過前面所有高度行數(shù)相加,得到最終的上邊位置
childTop -= (maxHeights.get(k) + itemSpace);
}
childTop += itemSpace;
}
childBottom = childTop + view.getMeasuredHeight();
view.layout(childLeft, childTop, childRight, childBottom);
addView(view);
}
}
}
}
public void setAdapter(Adapter adapter) {
mAdapter = adapter;
invalidate();
}
}
本文到此結(jié)束,如果有什么問題,歡迎一起討論。