Search code examples
androidspeech-to-text

Invoking setOnCheckedChangeListener without a button click


I have an application that gives the user the option of using buttons to click yes or no to a series of questions. I want to add handsfree functionality where the user says yes or no and it should access the same code block. I am however stumped as to how I an "virtually" invoke the setOnCheckedChangeListener event of the yes/no buttons to get to the code? Is it possible to make a virtual button call that invokes it? I have attached a snippet of code that hopefully sheds some light.

Code:

recognizerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
speech.startListening(recognizerIntent);

public void onResults(Bundle results)
{
    ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);

    for (String result : matches)
    {

        switch (result)
        {
            case "yes":
                speech_response_yes=true;
                break;
            case "no":
                speech_response_no=true;
                break;
        }
    }
}

answer.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()           {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId)
            {
                // checkedId is the RadioButton selected
                if (checkedId == R.id.yesButton || speech_response_yes) 
                {
                  ....perform relevant tasks
                }

Solution

  • By merely setting the radio buttons as checked, you will invoke the SetOnCheckChangedListener.

    for (int i=0;i<count;i++) {
        View o = answer.getChildAt(i);
        if (o instanceof RadioButton) {
    
          if (o.getId() == R.id.yourButton) { 
             o.setChecked(true);
          }
        }
    }