Question

I have toggle button which has android:onClick=onToggleClicked. I tried to reference the onToggleClicked method from the java code but the problem is, eclipse underscore the onToggleClicked with red and does not recognizes it. How to fix this error.

Imports:

import java.util.Set;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.os.Build;

JavaCode:

    if (myBluetoothAdapter == null) {
        tb_OnOFF.setEnabled(false);
        btnFind.setEnabled(false);
        btnPaired.setEnabled(false);
        tvStatusCaption.setText("Status: Not Supported.");
        Toast.makeText(getApplicationContext(), "Your Device Does Not Support " +
                "Bluetooth", Toast.LENGTH_LONG).show();
    } else {
        public void onToggleClicked (View view) {
            boolean on = ((ToggleButton) view).isChecked();
            if (on) {
                //enable bluetooth                  
            }

            if (!on) {
                //disable bluetooth
            }
        }
    }

XML:

<ToggleButton
    android:id="@+id/btnToggle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textOn="@string/toggle_turn_on"
    android:textOff="@string/toggle_turn_off"
    android:checked="true"
    android:onClick="onToggleClicked" />
Was it helpful?

Solution 2

USE THIS

mToggleButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
    if (mToggleButton.isChecked()) {
        //your code

    }
    else{
        //your code
    }
                }
            });

OTHER TIPS

onToggleClicked is a public method and needs to be attached to your Activity. You cannot use this method as an inner method inside onCreate method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top