I am trying to enable the user to stops and starts service which I am implementing from the Menu where the text is will be changed when he clicks it so I want to add ToggleButton
as option in the menu tool but nothing is being display in my case now. How can I fix it?
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<ToggleButton
android:id="@+id/toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="Off"
android:textOn="On" />
</menu>
MainActivity:
public class MainActivity extends ActionBarActivity {
ToggleButton tButton;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.toggle:
tButton = (ToggleButton) findViewById(R.id.toggle);
tButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (((ToggleButton) v).isChecked()) {
Intent i = new Intent(MainActivity.this,
TrackingService.class);
startService(i);
System.out.println("test is checked, start service");
} else {
// Stop the service when the Menu button clicks.
Intent i = new Intent(MainActivity.this,
TrackingService.class);
stopService(i);
System.out.println("test is NOT checked, stop service");
}
}
});
return true;
default:
return false;
}
}
}
Edit:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.checkable_menu:
if (isChecked = !item.isChecked()) {
item.setChecked(isChecked);
Intent i = new Intent(this, TrackingService.class);
startService(i);
System.out.println("test if onOptionsItemSelected");
} else {
Intent i = new Intent(this, TrackingService.class);
stopService(i);
System.out.println("test else onOptionsItemSelected");
}
return true;
default:
System.out
.println("test default onOptionsItemSelected was invoked.");
return false;
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…