在textview中处理计数器

时间:2016-05-04 10:08:08

标签: android

如何处理+和 - 在textview上我试过这种方式,但减去不起作用。每当我得到增量数量减去按钮没有工作

  public class HomeFragment extends Fragment {

    Button btnShirtPlus,btnShirtMinus;
    TextView text_quantity;
    Integer incrementValue;
    String counterDec;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_home,container,false);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        btnShirtMinus = (Button)view.findViewById(R.id.btnMinusShirt);
        btnShirtPlus = (Button)view.findViewById(R.id.btnPlusShirt);
        text_quantity = (TextView)view.findViewById(R.id.txtCounterShirt);

        btnShirtMinus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                counterDec = text_quantity.getText().toString();
                incrementValue = Integer.parseInt(counterDec);
                //counter -- ;
                text_quantity.setText(String.valueOf(incrementValue));
                Toast.makeText(getContext(), "Minus hit", Toast.LENGTH_SHORT).show();
            }
        });

        btnShirtPlus.setOnClickListener(new View.OnClickListener() {
            int counter = 0;
            @Override
            public void onClick(View v) {
               // counter ++;
                text_quantity.setText(String.valueOf(counter++));
                Toast.makeText(getContext(), "Plus hit" + counter, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

以下图片显示点击加号后发生的情况

1 个答案:

答案 0 :(得分:2)

你可以这样做:

添加按钮 -

btnShirtPlus.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                int value = Integer.parseInt(text_quantity.getText()
                        .toString().trim());
                value++;
                if (value >= 1) {
                    btnShirtMinus.setEnabled(true);
                }
                text_quantity.setText(String.valueOf(value));
            }
        });

对于删除按钮 -

btnShirtMinus.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                int value = Integer.parseInt(text_quantity.getText()
                        .toString().trim());
                --value;
                if (value == 0) {
                    btnShirtMinus.setEnabled(false);
                }
                text_quantity.setText(String.valueOf(value));
            }
        });