鸿洋的GitHub:/hongyangAndroid/FlowLayout
第一步:加依赖
implementation 'com.hyman:flowlayout-lib:1.1.2'
第二步:创建一个Adapter继承TagAdapter
public class MyFlowAdapter extends TagAdapter<String> {private Context context;public MyFlowAdapter(Context context,List<String> datas) {super(datas);this.context=context;}@Overridepublic View getView(FlowLayout parent, int position, String s) {LayoutInflater inflater = LayoutInflater.from(context);TextView tv = (TextView) inflater.inflate(R.layout.flow_item, parent, false);tv.setText(s);return tv;}/*** 选中时的回调方法* @param position* @param view*/@SuppressLint("ResourceAsColor")@Overridepublic void onSelected(int position, View view) {super.onSelected(position, view);view.setBackgroundColor(R.color.colorAccent);}/*** 默认的回调方法* @param position* @param view*/@SuppressLint("ResourceAsColor")@Overridepublic void unSelected(int position, View view) {super.unSelected(position, view);view.setBackgroundColor(R.color.colorPrimaryDark);}}
第三步:创建一个子布局
<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="/apk/res/android"android:id="@+id/tv"android:layout_width="wrap_content"android:layout_height="wrap_content"></TextView>
第四步:使用页面的布局
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="/apk/res/android"xmlns:app="/apk/res-auto"xmlns:tools="/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><!--max_select:-1为不限制选择数量,>=1的数字为控制选择tag的数量--><com.zhy.view.flowlayout.TagFlowLayoutandroid:padding="20dp"app:max_select="-1"android:id="@+id/flow"android:layout_width="match_parent"android:layout_height="wrap_content"></com.zhy.view.flowlayout.TagFlowLayout></LinearLayout>
第五步:在Activity中的使用方式
public class MainActivity extends AppCompatActivity {List<String> list = new ArrayList<>();private TagFlowLayout mFlow;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();initData();}private void initData() {for (int i = 0; i < 50; i++) {list.add("标签"+(i+i*20));}MyFlowAdapter adapter=new MyFlowAdapter(this,list);mFlow.setAdapter(adapter);//点击时的回调方法mFlow.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {@Overridepublic boolean onTagClick(View view, int position, FlowLayout parent) {Toast.makeText(MainActivity.this, "点击", Toast.LENGTH_SHORT).show();return true;}});//点击时回调所选中的集合mFlow.setOnSelectListener(new TagFlowLayout.OnSelectListener() {@Overridepublic void onSelected(Set<Integer> selectPosSet) {}});//预先设置选中adapter.setSelectedList(1,3,5,7,8,9);//选中的下标集合Set<Integer> selectedList = mFlow.getSelectedList();}private void initView() {mFlow = (TagFlowLayout) findViewById(R.id.flow);}}