購物車的加減器
阿新 • • 發佈:2018-12-01
//佈局加減器三個textview
<?xml version="1.0" encoding="utf-8"?><TextView android:background="#ffffff" android:layout_weight="1" android:id="@+id/sub_tv" android:layout_width="0dp" android:layout_height="match_parent" android:gravity="center" android:text="-" android:textSize="16sp" /> <TextView android:text="1" android:layout_marginLeft="2dp" android:background="#ffffff" android:layout_weight="1" android:id="@+id/product_number_tv" android:layout_width="0dp" android:layout_height="match_parent" android:gravity="center" /> <TextView android:layout_marginLeft="2dp" android:background="#ffffff" android:layout_weight="1" android:id="@+id/add_tv" android:layout_width="0dp" android:layout_height="match_parent" android:gravity="center" android:text="+" android:textSize="16sp" />
//利用組合式自定義控制元件實現加減器的操作
public class MyAddSubView extends LinearLayout implements View.OnClickListener {
private int number = 1;
private TextView sub_tv;
private TextView product_number_tv;
private TextView add_tv;
public MyAddSubView(Context context) { this(context, null); } public MyAddSubView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public MyAddSubView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); View view = inflate(context, R.layout.add_remove_view_layout, this); sub_tv = view.findViewById(R.id.sub_tv); product_number_tv = view.findViewById(R.id.product_number_tv); add_tv = view.findViewById(R.id.add_tv); sub_tv.setOnClickListener(this); add_tv.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.sub_tv: if (number > 1) { --number; product_number_tv.setText(number + ""); if (onNumberChangeListener != null) { onNumberChangeListener.onNumberChange(number); } } else { Toast.makeText(getContext(), "不能再少了", Toast.LENGTH_SHORT).show(); } break; case R.id.add_tv: ++number; product_number_tv.setText(number + ""); if (onNumberChangeListener != null) { onNumberChangeListener.onNumberChange(number); } break; } } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; product_number_tv.setText(number + ""); } OnNumberChangeListener onNumberChangeListener; public void setOnNumberChangeListener(OnNumberChangeListener onNumberChangeListener) { this.onNumberChangeListener = onNumberChangeListener; } public interface OnNumberChangeListener { void onNumberChange(int num); }
}