本文实例为大家分享了Android实现购物车加减商品操作的具体代码,供大家参考,具体内容如下
MainActivity.java
public class MainActivity extends AppCompatActivity { private Addand mAddand; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mAddand= findViewById(R.id.add); mAddand.setOnNumberChangedListener(new Addand.OnNumberChangedListener() { @Override public void OnNumberChanged(int vs) { Toast.makeText(MainActivity.this, vs+"", Toast.LENGTH_SHORT).show(); } }); } }
activity_main.xml
Addand.java
public class Addand extends FrameLayout implements View.OnClickListener{ private ImageView mImage1; private ImageView mImage2; private TextView mText; int value; public Addand(@NonNull Context context) { this(context,null); } public Addand(@NonNull Context context, @Nullable AttributeSet attrs) { this(context, attrs,0); } public Addand(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); findView(context); } private void findView(Context context) { View view = View.inflate(context, R.layout.add, this); mImage1 =view.findViewById(R.id.image1); mImage2 = view.findViewById(R.id.image2); mText = view.findViewById(R.id.text); value=getValue(); setValue(value); mImage1.setOnClickListener(this); mImage2.setOnClickListener(this); } private int vs=1; public int getValue() { //获取值 String trim = mText.getText().toString().trim(); if (!TextUtils.isEmpty(trim)){ Integer.valueOf(vs); } return vs; } public void setValue(int value) { mText.setText(value+""); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.image1: add(); break; case R.id.image2: jian(); break; } } private void jian() { if (vs>1){ vs--; setValue(vs); } mOnNumberChangedListener.OnNumberChanged(vs); } private void add() { if (vs<6){ vs++; setValue(vs); } mOnNumberChangedListener.OnNumberChanged(vs); } public interface OnNumberChangedListener{ void OnNumberChanged(int vs); } private OnNumberChangedListener mOnNumberChangedListener; public void setOnNumberChangedListener(OnNumberChangedListener onNumberChangedListener){ mOnNumberChangedListener=onNumberChangedListener; } }
add.xml
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。