Reputation: 4749
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!
Upvotes: 3
Views: 3774
Reputation: 974
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;
}
Upvotes: 2