Search code examples
javaandroidandroid-activity

How to restrict increment button if stock is 10?


I am new to Android. I'm trying to restrict increments if the value of stock is 10. The count value is set in textcount which is a TextView. plus and minus are button for increment and decrement. stockshow is textview and ITEM_QTY i added in getter setter method

plus.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        addtocart.setVisibility(View.VISIBLE);
        count++;
        textcount.setText(String.valueOf(count));
    }
});

minus.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        count--;
        textcount.setText(String.valueOf(count));
    }
});

stockshow.setText(country.getITEM_QTY());


Solution

  • You'll want to make use of the setEnabled() method of View to ensure that the plus button can no longer be clicked should the stock count be set to 10. Likewise, you'll also want to disable the minus button once the stock count reaches 0. You could create a method like this:

    private void checkBounds() {
        plus.setEnabled(count < 10);
        minus.setEnabled(count > 0);
    }
    

    And then use it in your listeners like so:

    plus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            addtocart.setVisibility(View.VISIBLE);
            count++;
            textcount.setText(String.valueOf(count));
            checkBounds();
        }
    });
    
    minus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            count--;
            textcount.setText(String.valueOf(count));
            checkBounds();
        }
    });