1

What I am basicaly trying is to access a variable inside a Fragment and get rid of it in my activity.

It worked to get the variable of the activity in my fragment but not the other way around:

what I did:

// get method of MainActivity
final MainActivity activity = (MainActivity) getActivity();

is it even possible to make this "the other way around"?

(Access variable of Fragment in my Activity)?

3 Answers 3

2

You need to implement listeners. You can read more about here:Communicating with Other Fragments

Here is a code example how to pass data (or null) from Activity to a Fragment:

public class FragmentA extends Fragment implements FragmentCommunicator{


@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    ((MainActivity)getActivity()).fragmentCommunicator = this;

}
@Override
public void passDataToFragment(String str) {
    //str is the string variable you pass from the Activity, it can be null...

    }
}}

Next the FragmentCommunicator Class:

public interface FragmentCommunicator{
public void passDataToFragment(String str);}

And the Activity:

 public class MainActivity extends FragmentActivity{

public FragmentCommunicator fragmentCommunicator;


public void someMethod(String someString) {

 fragmentCommunicator.passDataToFragment(someString);


}}

When you call passDataToFragment() from the Activity it will pass the string (or any other variable) to the fragment method passDataToFragment().

Sign up to request clarification or add additional context in comments.

Comments

0

You can get your fragment by id/tag from fragment manager and do whatever you want with them.

Comments

0

that's super easy. if you are adding your fragments in runtime (using FragmentManager) you are creating objects of that fragment...just keep the reference with you and you are good to call any function or access any variable of the fragment. e.g. you fragment is MyFragment

MyFragment mf = new MyFragment();

getSupportFragmentManger().beginTrans......you know the code to add a fragment then simply call any method...for say... change() by mf.change();

or you can do something like

MyFragment mf = (MyFragment) findFragmentById(R.id.container);
and then again mf.change();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.