Search code examples
androidandroid-recyclerviewandroid-menuandroid-viewholder

How to enable menu item with a click of items of recycler view?


I have a recycler view with checkboxes in InterestsActivity and I want to enable NEXT button on the toolbar after I got at least 4 checkboxes selected.

NEXT button is disabled in onCreateOptionsMenu(Menu menu)

 @Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.menu_interests_button, menu);
    nextBtn = menu.findItem(R.id.action_button);
    nextBtn.setEnabled(false);

    return true;
}

I have overridden onPrepareOptionsMenu(Menu menu) and trying to enable menu item there with a call to invalidateOptionsMenu() in onClick of my ViewHolder item..

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);

    MenuItem item = menu.findItem(R.id.action_button);
    if(interestMap.size()>=4)
    item.setEnabled(true);

    return true;
}

My bind method in ViewHolder

public void bind(final Topic subject) {
        interestMap=new HashMap<>();
        mSubjectCheckbox.setText(subject.getSubjectName());
        mSubjectCheckbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                interestMap.put(subject.getSubjectName(),true);
                if(interestMap.size()>=4)
                    InterestsActivity.this.invalidateOptionsMenu();

            }
        });
    }

But the button is not being enabled, am I doing right or missing anything?

 @Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    if (id == R.id.action_button) {
        mFirebaseUtil.mFirestore.collection("users").document(FirebaseUtil.getCurrentUserId()).collection("interests").add(interestMap).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
            @Override
            public void onSuccess(DocumentReference documentReference) {
                Intent setupIntent = new Intent(InterestsActivity.this, SetupActivity.class);
                startActivity(setupIntent);
                finish();
            }
        });
        return true;
    }

    return super.onOptionsItemSelected(item);
}

Please help me resolve this. Thanks in Advance.


Solution

  • There seems to be nothing wrong with this code.

    You should check if condition interestMap.size()>=4 gets correct value, that is your interestMap is populated correctly.