Home > OS >  How can I get MaterialSwitch id from activity in fragment in android?
How can I get MaterialSwitch id from activity in fragment in android?

Time:07-05

How can I get materialSwitch id in fragment from activity. switch which is in mainActivity but i want to check in fragment whether the switch is on or off. for example "if(switchMaterial.ischecked){ code... }" by calling the id from the mainActivity in fragment

I have tried this but it doesn't worked

MainActivity.java

    public SwitchMaterial switchMaterial;

Fragment.java

 if (((MainActivity) getActivity()).switchMaterial.isChecked()){
        Toast.makeText(getActivity(), "checked", Toast.LENGTH_SHORT).show();
    }else {
        Toast.makeText(getActivity(), "not checked", Toast.LENGTH_SHORT).show();
    }

Is this possible to call id from activity to fragment. If possible please help me out.

CodePudding user response:

You can try this on your way

MainActivity.java

static SwitchMaterial switchMaterial;

Fragment.java

if (MainActivity.switchMaterial.isChecked()){
        Toast.makeText(getActivity(), "checked", Toast.LENGTH_SHORT).show();
    }else {
        Toast.makeText(getActivity(), "not checked", Toast.LENGTH_SHORT).show();
    }

This should work but can make memory leak in some cases .. You may also try using SharedPreferences for example to avoid memory leaks

  • Related