2

Erm instead of using toggle button can I toggle icon in app bar instead?

like when I pressed my icon in the app bar it will change to other icon

Here is my menu_main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="course.examples.healthcare_application.MainActivity">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="1"
        android:title="@string/action_settings"
        app:showAsAction="never" />

    <!--lower value will be on the left-->
    <item
        android:id="@+id/Bluetooth_connect"
        android:icon="@drawable/ic_bluetooth_white_24dp"
        app:showAsAction="always"
        android:orderInCategory="2"
        android:title="@string/bluetooth_connect" />
</menu>

Code on main activity

 @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();

        //noinspection SimplifiableIfStatement

        if(id == R.id.Bluetooth_connect){
            Toast.makeText(getApplicationContext(), "Turned on", Toast.LENGTH_LONG).show();

        }

        return super.onOptionsItemSelected(item);
    }
}
Spotty
  • 197
  • 2
  • 2
  • 14

2 Answers2

1

To achieve the toggle effect, you could change the color of the button when it is clicked. If the icon is a drawable, the color can be set with the tint attribute.

In xml the tint can be set with

android:tint="@color/icon_pressed"

In code the tint can be set with

imageView.setColorFilter(Color.argb(255, 255, 255, 255));
Saket Mittal
  • 3,726
  • 3
  • 29
  • 49
Sam Moser
  • 31
  • 1
  • 4
0

You define them in a selector like this in your drawable folder:

button_state.xml

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:state_pressed="true" android:drawable="@drawable/pressed" />
    <item android:state_pressed="true" android:drawable="@drawable/initialpressed"/>
    <item android:state_checked="true" android:drawable="@drawable/on"/>
    <item android:drawable="@drawable/initial"/>
</selector>

Then define it in your button like this:

android:background="@drawable/button_state"
Mr Robot
  • 1,747
  • 6
  • 35
  • 67