简体   繁体   English

Android-如何从Fragment访问父活动中的getter方法

[英]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. 我有一个FragmentActivity,它具有我需要在Fragment中使用的值。

This is the way I do it, but I have no idea on how to access the getter in the FragmentActivity. 我就是这样做的,但是我不知道如何在FragmentActivity中访问getter。

ItemDetailActivity ItemDetailActivity

public class ItemDetailActivity extends FragmentActivity implements ActionBar.TabListener {

    public String getItem_id() {
        return item_id;
    }

    public String getUser_id() {
        return user_id;
    }
    ...
}

ItemPhotosFragment ItemPhotosFragment

public class ItemPhotosFragment extends Fragment {
    public ItemPhotosFragment() {
        user_id = getActivity().getUser_id();
    }
}

As you can see in the FragmentActivity, I'm implementing TabListener. 如您在FragmentActivity中看到的,我正在实现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. 从getActivity访问是一种最佳实践,因为我在这里看到了一些建议的解决方案。

type cast into parent activity: 类型转换为父活动:

write this code in onActivityCreated inside your fragment not in constructor: 将此代码写在片段内部的onActivityCreated而不是在构造函数中:

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 当片段成为活动的一部分时,将调用onActivityCreated ,这是getActivity()不返回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. 在活动中初始化片段时,可以执行myFragment.setArguments(Bundle 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 http://developer.android.com/training/basics/fragments/communicating.html#DefineInterface

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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