項目中有時候會有這樣的需求,好比興趣愛好的選擇、搜索歷史標籤等,自帶的Android控件實現起來賊麻煩,因此本身擼一個唄,固然前提是這個庫開發者必須用得簡潔高效,並且功能到位。android
一、最基本的功能,標籤佈局而且自動換行。git
二、自定義了各類styleable,在xml佈局文件就能夠設置tag的屬性。github
三、能夠單選、多選,這個全有開發者自由選擇,只要本身加background就完事。算法
四、最後一點,簡潔高效。編程
對,在使用以前看看效果,來,上效果圖數據結構
首先,引入這個庫多線程
這是GitHub地址自定義標籤佈局FloaTagLayout,源碼項目裏面有,這篇文章暫不說該控件的原理,以後會出源碼的分析。app
gradle:ide
compile 'com.jetlee:FlowTagLayout:1.0.1'
複製代碼
Maven:佈局
<dependency>
<groupId>com.jetlee</groupId>
<artifactId>FlowTagLayout</artifactId>
<version>1.0.1</version>
<type>pom</type>
</dependency>
複製代碼
把庫依賴到項目中後,在佈局中使用,並配置各類屬性
<com.jet.flowtaglayout.FlowTagLayout
android:id="@+id/flowTagLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:item_leftMargin="8dp" // tag的左外邊距
app:item_rightMargin="8dp" // tag的右外邊距
app:item_topMargin="8dp" // tag的上外邊距
app:item_bottomMargin="8dp" // tag的下外邊距
app:item_leftPadding="12dp" // tag的左內邊距
app:item_rightPadding="12dp" // tag的右內邊距
app:item_topPadding="6dp" // tag的上內邊距
app:item_bottomPadding="6dp" // tag的下內邊距
app:item_background="@drawable/ripple_gray" // tag的item背景效果
app:item_textColor="#F25A25" // tag的text顏色
app:item_textSize="16sp" // tag的text字體大小
/>
複製代碼
下面列出FlowTagLayout的重要方法(注意,這些方法能夠共用,也能夠只用一種,看各自的需求)
先準備幾條數據,都是tag的label
List<String> dataList = new ArrayList<>();
dataList.add("數據結構");
dataList.add("算法");
dataList.add("Java");
dataList.add("多線程編程");
// 添加tag
flowTagLayout.addTags(dataList); // 添加tag的列表,該方法會把以前的tags所有清空
flowTagLayout.addTag("Kotlin"); // 在尾部添加一個tag
flowTagLayout.addTagOfIndex(2,"自定義view"); // 在指定的位置插入tag,示例爲在index爲2,也就是第三個位置插入tag
// 移除tag
flowTagLayout.removeTag(); // 移除尾部tag
flowTagLayout.removeTagOfIndex(3); // 移除指定位置的tag,示例爲移除index爲3,也就是第四個tag移除
複製代碼
最後就是綁定點擊事件
flowTagLayout.setTagClickListener(new FlowTagLayout.OnTagClickListener() {
@Override
public void tagClick(int position) {
// getChildAt(position)方法在這很實用
flowTagLayout.getChildAt(position).setSelected(!flowTagLayout.getChildAt(position).isSelected());
}
});
複製代碼
這個庫的使用就是這麼簡單,喜歡的給個star唄,哈哈哈。