Android 自定义 TagView
先上效果:
class TagView @JvmOverloads constructor(context: Context,attrs: AttributeSet? = null,defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {private val tagContainer: FlexboxLayoutinit {orientation = VERTICALLayoutInflater.from(context).inflate(R.layout.view_tag_container, this, true)tagContainer = findViewById(R.id.tag_container)}/*** 添加单个标签*/fun addTag(tagText: String, tagColor: Int = R.color.tag_default_color) {val tagView = TextView(context).apply {text = tagTexttextSize = 10fsetTextColor(ContextCompat.getColor(context, R.color.tag_default_text_color))setPadding(24, 6, 24, 6) // 水平和垂直内边距// 创建圆角背景val drawable = GradientDrawable().apply {cornerRadius = 12f * context.resources.displayMetrics.densitysetColor(ContextCompat.getColor(context, tagColor))}background = drawable// 设置外边距val layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT).apply {marginEnd = (6 * context.resources.displayMetrics.density).toInt()bottomMargin = (6 * context.resources.displayMetrics.density).toInt()}this.layoutParams = layoutParams}tagContainer.addView(tagView)}/*** 批量添加标签*/fun addTags(tags: List<String>, tagColor: Int = R.color.tag_default_color) {tags.forEach { addTag(it, tagColor) }}/*** 清除所有标签*/fun clearTags() {tagContainer.removeAllViews()}
}
没有看到宽度计算,应为使用了 flexbox 。
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"><com.google.android.flexbox.FlexboxLayoutandroid:id="@+id/tag_container"android:layout_width="match_parent"android:layout_height="wrap_content"app:flexWrap="wrap"app:alignItems="flex_start"app:flexDirection="row" />
</merge>
更多内容:
https://blog.csdn.net/janronehoo/category_12368766.html?spm=1001.2014.3001.5482