2

I am trying to create a like and dislike button. I use Checkboxes to do so.

In the XML code I have two checkboxes one called like and the other dislike

I'm trying to toggle between the like and dislike buttons. Such that they both cannot be switched on at the same time.

public void onLike(View view) {
        if (dislike.isChecked()) {
            dislike.setChecked(false);
        }
        Toast.makeText(this,"liked",Toast.LENGTH_SHORT).show();
    }

The issue that I am having is that set setChecked(true) is not doing anything.

For more context, the XML for the checkbox is defined inside a fragment that has a cardview. Each item in the card view has the checkboxes.

the way I initialized the checkbox in the main activity is as follows: -

View cardViewLayout = getLayoutInflater().inflate(R.layout.text_row_item,null);
        like = (CheckBox) cardViewLayout.findViewById(R.id.like);
        dislike = (CheckBox) cardViewLayout.findViewById(R.id.dislike);

any ideas what's going on?

Omar Bitar
  • 53
  • 5
  • `setChecked(true) is not doing anything.` I dont see that code. Moreover you would not need it. – blackapps Feb 18 '22 at 09:58
  • `if (dislike.isChecked()) { dislike.setChecked(false);` Try: `if (like.isChecked()) { dislike.setChecked(false);` – blackapps Feb 18 '22 at 09:59
  • And ... RadioButton ? – blackapps Feb 18 '22 at 10:08
  • @blackapps you are correct. Using the RadioButton is ideal for this context. I just did so and it worked. However, I am still having issues with the `setCheck(true)`. I want to do so in the `onCreate` method. – Omar Bitar Feb 19 '22 at 00:15

1 Answers1

0

ok, I've figured out the solution. Since I am using a recycler view with a custom adapter I need to bind the onClick listener via an interface.

Here is a link to another post that will show the necessary steps to implement click listeners in adapters: https://stackoverflow.com/a/49969478/11379938

Omar Bitar
  • 53
  • 5