Question

I have a FragmentActivity with a FragmentPagerAdapter which holds a number of Fragment objects through which I can slide with a horizontal swipe.

I was wondering if I can access an element ("elementToBeChanged") in the FragmentActivity from within a Fragment object? I would like to pass a String from the Fragment class to TextView element which is in the FragmentActivity object.

public class GalleryPagerActivity extends FragmentActivity implements OnClickListener {

private TextView elementToBeChanged;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    super.setContentView(R.layout.gallery_pager);

    elementToBeChanged = (TextView) findViewById(R.id.tvTop);
    elementToBeChanged.setOnClickListener(this);

}
}

How would I have to do this? The TextView element has to be updated every time a Fragment object comes into sight (with a swipe).

It should look something like this:

public class GalleryFragment extends Fragment {

private FragmentActivity fa;
private LinearLayout ll;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    fa = super.getActivity();

    ll = (LinearLayout) inflater.inflate(R.layout.gallery_fragment, container, false);
...
// ////////
// UPDATE THE "TextView elementToBeChanged" object in the parent FragmentActivity class HERE WHENEVER THIS FRAGMENTS BECOMES ACTIVE/VISIBLE...
// ////////

    return ll;
}
Was it helpful?

Solution

In your GalleryPagerActivity create a function such as updateTextView(String text). That function will set the TextView to whatever the input value is. Then in your GalleryFragment simply call this function with the text to be displayed as such:

    ((GalleryPagerActivity)getActivity()).updateTextView("my text");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top