Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: how can fragment take a global variable of Activity

I have an activity with a global variable int x, how can a fragment get the current value of variable x of its activity ?

like image 536
esoni Avatar asked Sep 11 '12 07:09

esoni


People also ask

How do you pass data between fragments and activities?

So, to pass data from the MotherActivity to such a Fragment you will need to create private Strings/Bundles above the onCreate of your Mother activity - which you can fill with the data you want to pass to the fragments, and pass them on via a method created after the onCreate (here called getMyData()).

Can a fragment call an activity?

Best way of calling Activity from Fragment class is that make interface in Fragment and add onItemClick() method in that interface. Now implement it to your first activity and call second activity from there.

Why fragment is faster than activity?

I became a believer in Fragments in my last application. Whether or not they are computationally faster, they feel faster because you can swap them in and out basically instantaneously, including full support for the back stack if you do it right (call addToBackStack() on the transaction, or something very similar).

Can fragments be used without an activity?

It can't exist independently. We can't create multi-screen UI without using fragment in an activity, After using multiple fragments in a single activity, we can create a multi-screen UI. Fragment cannot be used without an Activity.


2 Answers

Either set the var as public static, or use

((MyActivity)getActivity()).getX() 
like image 196
Steelight Avatar answered Oct 09 '22 02:10

Steelight


Using a public static variable isn't the best way to communicate between an activity and a fragment. Check out this answer for other ways:

The Android documentation recommends using an interface when the Fragment wants communicate with the Activity. And when the Activity wants to communicate with the Fragment, the Activity should get a reference to the Fragment (with findFragmentById) and then call the Fragment's public method.

The reason for this is so that fragments are decoupled from the activity they are in. They can be reused in any activity. If you directly access a parent Activity or one of its global variables from within a fragment, you are no longer able to use that fragment in a different Activity.

like image 30
Suragch Avatar answered Oct 09 '22 02:10

Suragch