I would like to toggle the state of Wifi in options menu in Android. I would like to extend its functionality by showing two icons one for "switched on" and the other for "switched off". It should work in such a way that when a user presses the menu key:
Is this possible to do in the options menu ?
Any ideas as to how to change the icons according to its state ?
So far I am able to toggle the Wifi state by taking the user to a different activity. But if I can achieve it in the options menu. It would make the app more easy to use.
Thank you for your input and for your time.
here is the code for wifi on/off :
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.wifistate:
final WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if(wifi.isWifiEnabled()){
wifi.setWifiEnabled(false);
Drawable drawable = getResources().getDrawable(R.drawable.off);
item.setIcon(drawable);
}else{
Drawable drawable = getResources().getDrawable(R.drawable.on);
item.setIcon(drawable);
wifi.setWifiEnabled(true);
}
break;
}
return true;
<uses-permission
android:name="android.permission.ACCESS_WIFI_STATE" />
<?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android"><item android:id="@+id/wifistate" android:title="Off" android:icon="@drawable/off"/></menu>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.