啥都不说先看效果:
可实现:
1.加减功能
2.点击背景变色
3.有最大值和最小值限制
源码下载地址:https://github.com/junmei520/JMAddSubView
现如今,无论什么软件都避免不了陷入”盈利“的爱河。这也是人之常情,唯有资金全备,才会有下文可谈。于是乎,我也开始学习做与商城有关的项目啦。
我发现在商城购物车模块,这种简单的加减功能,如若直接零散地写在代码中,还要对它进行各种处理,会显得代码凌乱而臃肿。
于是我便把这个控件及其内部的处理逻辑都封装在一个类中,并对外提供接口,以方便外界监听到数字的变化,最后我还自定义了属性,以便设置默认值以及获取属性。
这样再用起来就特别方便了。
实现的思路
1.自定义加减控件的布局和样式
布局 number_add_sub_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/selector_number_add_sub"
android:orientation="horizontal">
<Button
android:id="@+id/btn_sub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bg_btn_style_white"
android:padding="5dp"
android:text="-"
android:textColor="#000000"
android:textSize="20sp" />
<TextView
android:id="@+id/tv_num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:minWidth="100dp"
android:text="1" />
<Button
android:id="@+id/btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bg_btn_style_white"
android:padding="5dp"
android:text="+"android:textColor="#000000"
android:textSize="20sp" />
</LinearLayout>
样式 selector_number_add_sub.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="2dp" />
<stroke
android:width="1dp"
android:color="#dddddd" />
<solid android:color="#FFFFFF" />
</shape>
按钮背景样式 bg_btn_style_white.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item