Android实践: 一步实现图标文本+小红点
2017-02-04 本文已影响1411人
AssIstne
图标+文本作为一个按钮这种形式在国内大部分app都会使用.

虽然TextView
可以包含图标, 但是存在问题,

当你指定了
TextView
的高度时, 图标和文本之间的间距并不等于drawablePadding
.
所以当使用TextView
实现的时候, TextView
只能是wrap_content
, 如果这个按钮是有指定尺寸并且可以点击的话, 那么单纯使用TextView
就不能满足要求了, 需要在外部嵌套一个FrameLayout
来捕捉点击事件.
当一个app有多个这种按钮的时候(通常都有好几个, 底部tab按钮, 个人中心的按钮等等), 这种实现显得非常臃肿.如果还需要实现"小红点"的需求, 则更加麻烦了.
另外值得一提的是, TextView
是一个比较"重"的控件, SDK24中的源码超过1W行, 单纯的显示静态文本作为按钮, 显得有点大材小用.
所以写了一个控件来满足需要:
这个控件包含图标, 文本和红点以及红点内的文本. 可以任意设置元素的大小, 位置和内容. 能够满足常见的需求.
通过gradle添加依赖:
compile 'com.assistne.android:icon-dot-text-view:1.0'
一个控件满足所有需要:
<com.assistne.icondottextview.IconDotTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:text="Category"
app:icon="@drawable/ic_shopping_cart_black_48dp"
app:dot_visible="true"
app:dot_text="400"
/>
效果如图:

源码已经上传GitHub-IconDotTextView
欢迎提意见和issue :)
能帮到你的话, 点个star吧~ >-<