Change State of ToggleButton programmatically

1.5k views Asked by At

I have placed a togglebutton with id toggleButton

and I am using the code below to check if it's on or off

public void toggleClick(View view){

boolean on = ((ToggleButton) view).isChecked();
if(on){

}else{

}

}

Everything works fine.. I am trying to change the state of the toggle button, I tried a lot of codes through internet but none changes the state of the toggle to off.

I tried this:

ToggleButton toggleButtons;
toggleButtons  = (ToggleButton) findViewById(R.id.toggleButton); //In onCreate
toggleButtons.setChecked(false);

any ideas please?

2

There are 2 answers

0
eyllanesc On BEST ANSWER

Use setChecked(boolean checked) by example:

toggleButtons.setChecked(true)
0
kavita On

I ended up using Toggle feature using ImageButton. The code below works fine.

 *

private ImageButton ib;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //......
               ib = (ImageButton) rootView.findViewById(R.id.imagefavouriteButton);
                if (checkFavorite()) {
                    ib.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.fav_on));
                } else {
                    ib.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.fav_off));
                }
                ib.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (checkFavorite()) {
                            remFromFav();
                        } else {
                            addFavorites();
                        }
                    }
                });
    //.....
 }
    private boolean checkFavorite(){// code to check in db}
    public void addFavorites() {
        ib.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.fav_on));
        Toast.makeText(getActivity(), "Added ...", Toast.LENGTH_SHORT).show();
    }
    public void remFromFav() {
        ib.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.fav_off));
        Toast.makeText(getActivity(), "Removed ...", Toast.LENGTH_SHORT).show();
    }

Hope this helps you.