Android App - Java - ToggleButton

1.4k views Asked by At

I searched over google and this site but didn't find a working answer. I'm currently developing an android app and i've got toggle buttons in my view. But I can't check if they are checked. Had the same problem with CheckBoxes (after that was not working I tried it with ToggleButtons)

My view XML Code for the Toggle button:

<ToggleButton 
android:id="@+id/tglLoginStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="10px"
android:layout_y="152px"
android:textOn="Automatische Login An"
android:textOff="Automatische Login Aus"
>
</ToggleButton>

I tried this method:

tglLoginStart = (ToggleButton) findViewById(R.id.tglLoginStart);
if(tglLoginStart.isChecked())
{
    myDB.execSQL("UPDATE " + MY_DB_TABLE + " SET `value`='1' WHERE `name`='autologin'");
}
else
{
    myDB.execSQL("UPDATE " + MY_DB_TABLE + " SET `value`='0' WHERE `name`='autologin'");
}

And this method:

tglLoginStart.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            // Perform action on clicks
            if (tglLoginStart.isChecked()) {
                myDB.execSQL("UPDATE " + MY_DB_TABLE + " SET `value`='1' WHERE `name`='autologin'");
            } else {
                myDB.execSQL("UPDATE " + MY_DB_TABLE + " SET `value`='0' WHERE `name`='autologin'");
            }
        }
    });

But everytime it writes a 0 into the database! Has anyone an idea how to get the "real" state?

2

There are 2 answers

0
Dimitris Makris On

Try to use this: http://developer.android.com/reference/android/widget/CompoundButton.html#setOnCheckedChangeListener%28android.widget.CompoundButton.OnCheckedChangeListener%29

Normally, this should be triggered when you check/uncheck the ToggleButton.

Hope this helps!

0
Zeeshan On

Try This.

tglLoginStart.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                                    if(isChecked)
                                    {
                                         //do you work
                                    }
                                    else {
                                       //do otherwise
                                    }
            }
}