The project needs to use a control that records the order quantity. The result is that each time you click this control, the value in it will be automatically added until the maximum value is increased and then added again from the beginning. Previously, the default TextView was used for implementation. However, considering that this control is used in multiple projects, we decided to customize it.
(Control)
1. Previous implementation methods
int count = Integer.parseInt(amount.getText().toString());amount.setText(String.valueOf(count % 5 + 1));
2. Custom View Method
First define a View, called AmountView, inherited from TextView. The Code is as follows:
Import android. content. context; import android. util. attributeSet; import android. view. motionEvent; import android. widget. textView;/*** custom UI control, record the number of dishes ** @ school University of South China * @ date 2014.01 */public class AmountView extends TextView {/*** maximum number of copies */private int mMaxAmount = 5; /*** number of currently displayed copies */private int mAmount = 1; public AmountView (Context context) {super (context); setText (mAmount + "");} public AmountView (Context context, AttributeSet attrs) {super (context, attrs); setText (mAmount + "");} public AmountView (Context context, AttributeSet attrs, int defStyle) {super (context, attrs, defStyle); setText (mAmount + "") ;}@ Overridepublic boolean onTouchEvent (MotionEvent event) {if (event. getAction () = MotionEvent. ACTION_UP) {mAmount = mAmount % mMaxAmount + 1; setText (mAmount + ""); System. out. println ("AmoutView onTouchEvent");} return super. onTouchEvent (event);} public void setMaxAmount (int maxAmount) {mMaxAmount = maxAmount;} public void setAmount (int amount) {this. mAmount = amount; setText ("" + mAmount );}}
Note the following:
(1) The default three constructor methods must be implemented.
(2) the parameter of the setText method is Charsequece, And the int type parameter cannot be passed. Therefore, the mAmount is followed by double quotation marks.
(3) Handling click events in the onTouchEvent () method
Then, declare the control with the complete package name in the layout file.