Search code examples
androidtogglebutton

How to identify mute/unmute click - SOLVE


my problem is following: I want indentify (the keyevent) when the user click in the mute/unmute button and so change the satus of toggle button.

One image to understand better: https://lh6.googleusercontent.com/-yHjyvtCiyac/Ul6uQz_Ga2I/AAAAAAAAAiY/Ug06zyq7_Vg/w619-h81-no/volumebar.jpg

How do this?

Thanks.

Sorry for my english. I use Google Translator for do this >.<


Update: The mute/unmute button in XML file :

<ToggleButton 
android:id="@+id/toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/audiobtn"
android:textOn="" 
android:textOff="" />

Last Update: The problem was solved using the BroadcastReceiver class. Thanks for the help!


Solution

  • For Toggle Button

    add this line in toggle button xml

    android:onClick="onToggleClicked"
    

    Now in your activity class set this listener as

    public void onToggleClicked(View view) {
        // Is the toggle on?
        boolean on = ((ToggleButton) view).isChecked();
    
        if (on) {
            // set image for on state 
        } else {
          // set image for off state 
        }
    }
    

    More info for Toggle button can be find here

    For simple button

    Step 1 Create object on your button Button muteBtn=(Button)findViewById(R.id.mute_btn);

    Step 2 Create the click listener of this button and change it to pressed/non pressed state using a boolean which stores its state like this.

    boolean muteBtnSelection;
    
    muteBtn.setOnClickListener(new OnClickListener() {
    
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (muteBtnSelection) {
    
                    muteBtnSelection=false;
    
                    // set yout image for  mutebtn_pressed
                    muteBtn.setBackground(R.drawable.mutebtn_pressed);
    
                } else {
                    muteBtnSelection=true;
    
                    // set yout image for  mutebtn_not_pressed
                    muteBtn.setBackground(R.drawable.mutebtn_not_pressed);
    
                }
    
    
    
            }
        });
    

    in this way you can toggle between pressed and non pressed state.