我们要展示很多标签时,可能并不知道有多少个标签。标签的内容为多长。下面介绍比较快的方法实现这种效果。
1.添加依赖compile 'com.zhy:flowlayout-lib:1.0.3'
2.布局文件max_select="-1"能选中的个数 auto_select_effect=”true | false”设置点击效果,默认显示
<com.zhy.view.flowlayout.TagFlowLayout
android:layout_marginTop="@dimen/dp_15"
android:id="@+id/search_page_flowlayout"
zhy:max_select="-1"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
3.标签TextView及风格的设置
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/flowlayout_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="@drawable/flowlayout_shap"
android:text="Helloworld"
android:textColor="@color/black">
</TextView>
4.这里TextView用到了shap风格: color 选中标签颜色
blackground | drawable 已选中背景。这里我引用了一个shape风格
state_checked 是否显示选中状态效果。
blackground | drawable 未选中背景。
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/theme"
android:drawable="@drawable/button_shape"
android:state_checked="true"></item>
<item android:drawable="@drawable/bg_black_shape"></item>
</selector>
5.数据源:final LayoutInflater mInflater = LayoutInflater.from(SearchPageActivity.this);
search_page_flowlayout.setAdapter(new TagAdapter<String>(mVals)
{
@Override
public View getView(FlowLayout parent, int position, String s)
{
TextView tv = (TextView) mInflater.inflate(R.layout.search_page_flowlayout_tv,
search_page_flowlayout, false);
tv.setText(s);
return tv;
}
});
6.监听标签点击事件:
search_page_flowlayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener()
{
@Override
public boolean onTagClick(View view, int position, FlowLayout parent)
{
Toast.makeText(SearchPageActivity.this, mVals[position], Toast.LENGTH_SHORT).show();
//view.setVisibility(View.GONE);
return true;
}
});
7.结束语。
效果很好实现,具体功能看要看你自己的项目需求了。