Hello). I am writing a mobile application android. You need a CheckBox in the header of the menu, since there is no such item as a regular CheckBox , added an item and enabled checkable in its settings, how do you write an event handler now? The handler like the usual CheckBox does not fit. Does not work). my non working code:

 if (id == R.id.action_online) { final TextView textView = (TextView) findViewById(R.id.hello); final CheckBox checkbox = (CheckBox) findViewById(R.id.action_online); checkbox.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { if (checkbox.isChecked()) { textView.setText("WTF!!!"); } else { textView.setText("WTF!!!"); } } }); } 

I tried to write CheckedTextView instead of the usual CheckBox , it doesn’t work, and Checkable doesn’t have the setOnClickListener attribute. setOnClickListener help)) I tried to write like in these articles: 1) http://developer.alexanderklimov.ru/android/views/checkbox.php 2) https://metanit.com/java/android/4.3.php

  • Unclear. You have a CheckBox | now? - Flippy

2 answers 2

You must listen to another listener:

 checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) { //blah-blah } } ); 
  • Unfortunately it does not work ((The application crashes: (( - Diq

Found a solution)

  @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); final TextView textView = (TextView) findViewById(R.id.hello); if (id == R.id.action_online) { if (item.isChecked()){ textView.setText("text true!"); item.setChecked(false); } else { textView.setText("text false!"); item.setChecked(true); } } return super.onOptionsItemSelected(item); } 
  • You wanted the listener, but here you just check the status of the checkbox - there is an incorrect wording of the question. - Barmaley