既发现TextView的妙用之后,在开发中又用类似的方法实现icon+text的扭按,之所以这样实现,是因为需求要求有类是开关状态,选中时同时改变图片和文字,并保持选中效果,CheckBox就兼具选中和图文(icon+text)特性,网上也有很多例子,不过大多都不尽完美,有各种适配问题,一般都是利用android:button的属性换成自己的图标,这时就会有个图标和文字间距的问题,网上一般的做法是设置android:paddingLeft,但是设置同样的dp不同分辨率的手机就会间距不一致,就连同样是小米系列的手机效果不一样,体验很差,那怎么实现呢?接下来,分享一下我的心得,欢迎交流指正。
还是先看效果:
如图所示点击后图标和文字同时变成蓝色,如果icon和text分开用ImageView和TextView画UI的话,需要代码手动感干预的就比较多,所以用CheckBox+selector就是一个不错的选择。来先看代码,在说注意的细节点。
<LinearLayout
android:id="@+id/bottom_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center_horizontal|center_vertical"
android:orientation="horizontal"
android:paddingLeft="" >
<LinearLayout
android:id="@+id/setting_no_picture_layout"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_weight="1"
android:background="@color/transparent"
android:gravity="center_horizontal|center_vertical"
android:orientation="horizontal" >
<CheckBox
android:id="@+id/setting_picture_check_box"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:drawableLeft="@drawable/sidebar_pic_or_nopic_toggle_selector"
android:drawablePadding="10dp"
android:button="@null"
android:background="@color/transparent"
android:text="@string/picture_or_nopic"
android:textColor="@drawable/checkbox_text_selector"
android:textSize="14sp" />
</LinearLayout>
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:layout_marginBottom="15dp"
android:layout_marginTop="15dp"
android:background="@color/slide_menu_listview_divider" />
<LinearLayout
android:id="@+id/setting_night_layout"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_weight="1"
android:background="@color/transparent"
android:gravity="center_horizontal|center_vertical" >
<CheckBox
android:id="@+id/setting_night_check_box"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:drawableLeft="@drawable/sidebar_day_or_night_toggle_selector"
android:drawablePadding="8dp"
android:button="@null"
android:background="@color/transparent"
android:text="@string/day_or_night"
android:textColor="@drawable/checkbox_text_selector"
android:textSize="14sp" />
</LinearLayout>
</LinearLayout>
1.为什么不在android:button中直接设置selector?
是这样的,如果简单的替换还原有的button图标,就需要设置android:paddingLeft来改变icon和text之间的间距,这样适配起来很麻烦,不同分辨变率的手机显示间距不一致。用android:drawableLeft则可以很灵活的控制icon相对text的位置,并且不同分辨率间距也可以保持一致。
2.为什么要将android:background设置透明颜色呢?
这个是实践得出来的,因为在做侧边栏底部菜单时,在外层LinearLayout中设置gravity水平垂直居中时,小米4的怎么看着都不居中,而在小米2s和红米上都是正常的,后来设置background为透明就显示正常了。
以上就是我的一点心得,希望对大家有所帮助。