简体   繁体   中英

Getting A Boolean Value From Activity In Fragment

It's weird this question hasn't been asked yet.

I need to check phone storage in my activity and get the returned value in my fragment

/*MainActivity*/
boolean hasLowStorage(){
    IntentFilter lowStorageFilter = new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW);
    return registerReceiver(null, lowStorageFilter) != null;
}

When calling a void method from an activity, we do this:

 /*fragment*/
((MainActivity) getActivity()).yourMethod();

How do we call for the value in the boolean case from the fragment?

Change scope of method to public and try again.

// MainActivity

public boolean hasLowStorage(){
        IntentFilter lowStorageFilter = new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW);
        return registerReceiver(null, lowStorageFilter) != null;
    }

//Fragment

    boolean bolValue = ((MainActivity) getActivity()).hasLowStorage();

尝试这个:

boolean yourValue = ((MainActivity) getActivity()).hasLowStorage();

Make it public static like this

 /*MainActivity*/
 public static boolean hasLowStorage(){
 IntentFilter lowStorageFilter = new 
 IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW);
 return registerReceiver(null, lowStorageFilter) != null;
 }

And call it like

 boolean yourValue = 
 MainActivity.hasLowStorage();

Happy coding :)

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