Android实现仿淘宝购物车增加和减少商品数量功能demo示例

  package jczb.shoping.ui;

  import android.R.string;

  import android.app.Activity;

  import android.os.Bundle;

  import android.text.Editable;

  import android.text.TextWatcher;

  import android.view.View;

  import android.view.View.OnClickListener;

  import android.widget.Button;

  import android.widget.EditText;

  import android.widget.Toast;

  public class ShoppingCartItemActivity extends Activity {

  private Button btAdd, btReduce;

  private EditText edtNumber;

  int num=0; //数量

  protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_shoppingcart_item);

  btAdd=(Button)findViewById(R.id.cart_pro_reduce);

  btReduce=(Button) findViewById(R.id.cart_pro_add);

  edtNumber=(EditText) findViewById(R.id.cart_pro_count);

  btAdd.setTag("+");

  btReduce.setTag("-");

  //设置输入类型为数字

  edtNumber.setInputType(android.text.InputType.TYPE_CLASS_NUMBER);

  edtNumber.setText(String.valueOf(num));

  SetViewListener();

  }

  /**

  * 设置文本变化相关监听事件

  */

  private void SetViewListener()

  {

  btAdd.setOnClickListener(new OnButtonClickListener());

  btReduce.setOnClickListener(new OnButtonClickListener());

  edtNumber.addTextChangedListener(new OnTextChangeListener());

  }

  /**

  * 加减按钮事件监听器

  *

  *

  */

  class OnButtonClickListener implements OnClickListener

  {

  @Override

  public void onClick(View v)

  {

  String numString = edtNumber.getText().toString();

  if (numString == null || numString.equals(""))

  {

  num = 0;

  edtNumber.setText("0");

  } else

  {

  if (v.getTag().equals("-"))

  {

  if (++num < 0) //先加,再判断

  {

  num--;

  Toast.makeText(ShoppingCartItemActivity.this, "请输入一个大于0的数字",

  Toast.LENGTH_SHORT).show();

  } else

  {

  edtNumber.setText(String.valueOf(num));

  }

  } else if (v.getTag().equals("+"))

  {

  if (--num < 0) //先减,再判断

  {

  num++;

  Toast.makeText(ShoppingCartItemActivity.this, "请输入一个大于0的数字",

  Toast.LENGTH_SHORT).show();

  } else

  {

  edtNumber.setText(String.valueOf(num));

  }

  }

  }

  }

  }

  /**

  * EditText输入变化事件监听器

  */

  class OnTextChangeListener implements TextWatcher

  {

  @Override

  public void afterTextChanged(Editable s)

  {

  String numString = s.toString();

  if(numString == null || numString.equals(""))

  {

  num = 0;

  }

  else {

  int numInt = Integer.parseInt(numString);

  if (numInt < 0)

  {

  Toast.makeText(ShoppingCartItemActivity.this, "请输入一个大于0的数字",

  Toast.LENGTH_SHORT).show();

  } else

  {

  //设置EditText光标位置 为文本末端

  edtNumber.setSelection(edtNumber.getText().toString().length());

  num = numInt;

  }

  }

  }

  @Override

  public void beforeTextChanged(CharSequence s, int start, int count,

  int after)

  {

  }

  @Override

  public void onTextChanged(CharSequence s, int start, int before,

  int count)

  {

  }

  }

  }