实现购物车那种加减效果

public class MainActivity extends AppCompatActivity {
private ImageView img1, img2;
private TextView tv1;
private int mNumber = 0;
private int mMaxNumber = 99;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img1 = (ImageView) findViewById(R.id.iv1);
img2 = (ImageView) findViewById(R.id.iv2);
tv1 = (TextView) findViewById(R.id.tv);
img1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mNumber > 0) {
mNumber--;
}
setNumberText(mNumber + "");
}
});
img2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mNumber < mMaxNumber) {
mNumber++;
}
setNumberText(mNumber + "");
}
});

}

private void setNumberText(String s) {
tv1.setText(s);
mNumber = Integer.valueOf(s);
if (mAddAndSubtractOnClickListener != null) {
mAddAndSubtractOnClickListener.numberChange(mNumber);
}

}

private AddAndSubtractOnClickListener mAddAndSubtractOnClickListener;

public void setAddAndSubtractOnClickListener(AddAndSubtractOnClickListener addAndSubtractOnClickListener) {
mAddAndSubtractOnClickListener = addAndSubtractOnClickListener;
}

/**
* 加减按钮回调接口
*/
public interface AddAndSubtractOnClickListener {
void numberChange(int num);
}

}

  

posted @ 2016-08-09 15:37  世杰这么大  阅读(495)  评论(0编辑  收藏  举报