简体   繁体   中英

Android - How to access a getter method in parent Activity from Fragment

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:

  1. While initializing the fragment in activity, you can do myFragment.setArguments(Bundle bundle) and you can put your params in this bundle.
  2. The other way is mentioned in above example.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM