Reputation: 38902
I have 2 Fragments.
FirstFragment has only a button. When user press the button, the SecondFragment is shown.
Both fragments are in backstack. So, when SecondFragment is shown, if user press physical back button, the FirstFragment will be shown.
Everything works fine at this point.
Now, on SecondFragment layout, I added an ToggleButton
:
<ToggleButton
android:id="@+id/my_toggle"
android:checked="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="@string/on"
android:textOff="@string/off"
/>
My SecondFragment.java :
public class SecondFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle){
super.onCreateView(inflater, container, savedInstanceState);
//My Toggle Button
myToggleBtn.setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
Log.v("*TOGGLE CHECK CHANGED*",String.valueOf(isChecked));
if(isChecked){
//DO SOME THING
}else{
//DO SOMETHING ELSE
}
}
});
return inflater.inflate(R.layout.second_layout, null);
}
...
@Override
public void onDestroy(){
super.onDestroy();
//Set my toggle button to unchecked status,when leave this fragment
myToggleBtn.setChecked(false);
}
}
The toggle button works fine on my SecondFragment. BUT, if now I press the toggle button to check it(so it changed to checked status), then press physical back button to go back to FirstFragment (onDestroy() is called which set toggle button to unchecked status) , and then come to SecondFragment again, surprisingly, at this moment, the ToggleButton
is checked at run time, and I noticed from LogCat, the OnCheckedChangeListener()
is invoked at run time too, why?
P.S.: LogCat shows that onDestroy() is called when leaving SecondFragment
Upvotes: 0
Views: 1994
Reputation: 38902
After I moved myToggleBtn.setChecked(false);
from onDestroy()
to onStop()
, the problem get solved. Thanks.
Upvotes: 1