Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling activity Method from inside fragment

I'm trying to pass a value to a fragment from its container activity.

I was trying do do it this way:

I have this method in the Activity.

public int showMode(){return Mode;} 

And this method in the Fragment:

public int getModeFromActivity(){
    int i;
    i = getActivity().showMode;
        return i;

but it gives me the error in the fragment method: showMode cannot be resolved or is not a field

Can anyone help me fix this? thanks!

like image 873
tyb Avatar asked Mar 21 '26 07:03

tyb


1 Answers

Your approach is wrong.

Here are two ways to get this job done in Android.

1.) Define an integer mode inside your Fragment. Change the Fragment's contructor to

FragmentName(int mode){
    this.mode = mode;
}

So you can read the mode variable in your Activity and can pass it to the Fragment at it's creation.

2.) Another way would be an Interface so your Fragment knows that its Parent Activity implements your Method! So you have to change the Fragment to something like this

InterfaceName mInterface;
FragmentName(MyInterfaceName interface){
    mInterface = interface;
}

public int getModeFromActivity(){
int i;
i = mInterface.showMode();
    return i;
}
like image 136
caiuspb Avatar answered Mar 22 '26 19:03

caiuspb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!