I’m trying to get a ToggleButton to switch the text in a TextView back and forth between two types of text. When I click the first time, it switches the default text to the alternate text but will not switch it back when I click it again. Here is my code:
ELswitch = (ToggleButton)findViewById(R.id.toggleButton1);
ELswitch.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(ELswitch.isEnabled()==true)
{
InputStream iFile = getResources().openRawResource(R.raw.raw_text_file_alternate);
try {
text.setText(inputStreamToString(iFile));
text.setFocusable(false);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
InputStream iFile = getResources().openRawResource(R.raw.raw_text_file_default);
try {
text.setText(inputStreamToString(iFile));
text.setFocusable(false);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
One suggestion I received to eliminate the problem was just to use a regular button and a counter and mod by 2. It seems like there should be a way to do this from a ToggleButton though. I think I might be instantiating the ToggleButton incorrectly or using the if-statements incorrectly but I can’t find the error. Any ideas?
It looks like your comparison is for:
Which would just tell you that the switch is enabled or not, not whether or not it is checked. You may want to change that to check if it is checked:
You can find more information about the Toggle button in the following guide/documentation:
http://developer.android.com/reference/android/widget/ToggleButton.html
From your question, it also seems that you may want to use an OnCheckedChangeListener instead of your OnClickListener. As example for this can be found in the guide below:
http://developer.android.com/guide/topics/ui/controls/togglebutton.html
Hopefully that helps!