版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
想要实现的效果:
本来感觉挺简单的 就是写一个横向的recyclerview,但是一写起来才发现根本不是我想象的那样,可以看出它的列表是根据屏幕和显示内容的宽度进行屏幕适配的 然后我像百度一下却不知道到底该怎么百度,最后自己还是找到了 然后将次demo分享出来
废话不多说,直接撸代码
1.导入库依赖
implementation 'com.hyman:flowlayout-lib:1.1.2'
2.在布局中对于控件的引用
<com.zhy.view.flowlayout.TagFlowLayout
android:id="@+id/tagfl"
android:background="#F0F0F0"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:max_select="1" />
注意:max_select:-1为不限制选择数量,>=1的数字为控制选择tag的数量 (这里是只能单选)
3.item布局
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/item_tag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:padding="10dp"
android:layout_margin="10dp"
android:text="标签"
android:background="@drawable/yuan"
/>
重点(精华就在这了):
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<corners android:radius="30dip" />
<solid android:color="#FFFFFF" />
<!-- 设置边框宽度和颜色 -->
<!--<stroke-->
<!--android:width="1dip"-->
<!--android:color="#000000" />-->
</shape>
对于item文本控件设置圆角以及边框哟
4.在活动中的引用
public class Main3Activity extends AppCompatActivity {
private TagFlowLayout tagFlowLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
tagFlowLayout = findViewById(R.id.tagfl);
initView();
}
private void initView() {
List<String> datas = new ArrayList<>();
datas.add("小花花");
datas.add("撒旦撒嗲基地啊实打实");
datas.add("a");
datas.add("弟弟救我");
datas.add("拉拉");
datas.add("德玛西亚");
datas.add("哈哈");datas.add("哼");
final String[] name = {"#990033","#CC6699","#99FFFF","#66FF66","#99CC00","#FF00FF","#FFCCFF","#663399","#FF0000"};
TagAdapter<String> adapter= new TagAdapter<String>(datas) {
@Override
public View getView(FlowLayout parent, int position, String o) {
TextView view = (TextView) LayoutInflater.from(Main3Activity.this).inflate(R.layout.item_tag, parent,false);
view.setText(o);
view.setTextColor(Color.parseColor(name[position]));
return view;
}
};
tagFlowLayout.setAdapter(adapter);
tagFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {//选中事件
@Override
public boolean onTagClick(View view, int position, FlowLayout parent) {
Log.i("点击","a"+position);
return false;
}
});
}
}
然后就是我实现的效果图:
希望能够对你有帮助哟 谢谢谢谢!