I have a FragmentActivity that has the values I needed to be used in a Fragment.
This is the way I do it, but I have no idea on how to access the getter in the FragmentActivity.
ItemDetailActivity
public class ItemDetailActivity extends FragmentActivity implements ActionBar.TabListener {
public String getItem_id() {
return item_id;
}
public String getUser_id() {
return user_id;
}
...
}
ItemPhotosFragment
public class ItemPhotosFragment extends Fragment {
public ItemPhotosFragment() {
user_id = getActivity().getUser_id();
}
}
As you can see in the FragmentActivity, I'm implementing TabListener. So I'm want to pass the values to all tabs (fragments).
How do I do this? Is accessing from getActivity a best practice because I saw some of the solutions here suggesting it.
type cast into parent activity:
write this code in onActivityCreated
inside your fragment not in constructor:
user_id =((ItemDetailActivity )getActivity()).getUser_id();
It's about fragment's life-cycle . onActivityCreated
is called when fragment becomes part of the activity and this is the first callback from where getActivity() doesn't return null
There are two ways of doing this:
myFragment.setArguments(Bundle bundle)
and you can put your params in this bundle. Above solution provided are good. i think the same can be done in a much cleaner way using delegation pattern. Here is the link for this. http://developer.android.com/training/basics/fragments/communicating.html#DefineInterface
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.