简体   繁体   中英

Change State of ToggleButton programmatically

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?

通过示例使用setChecked(boolean checked)

toggleButtons.setChecked(true)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM