Android的 - 如何从片段访问getter方法​​在父活动 [英] Android - How to access a getter method in parent Activity from Fragment

查看:117
本文介绍了Android的 - 如何从片段访问getter方法​​在父活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有了我需要在一个片段中使用。的值的FragmentActivity

I have a FragmentActivity that has the values I needed to be used in a Fragment.

这是我做的方式,但我对如何访问吸气的FragmentActivity不知道。

This is the way I do it, but I have no idea on how to access the getter in the FragmentActivity.

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();
    }
}

正如你可以在FragmentActivity看,我实现TabListener。所以我想的价值观传递给所有标签(片段)。

As you can see in the FragmentActivity, I'm implementing TabListener. So I'm want to pass the values to all tabs (fragments).

我如何做到这一点?从getActivity访问最佳实践,因为我看到了一些解决方案在这里暗示吧。

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:

onActivityCreated 这code的片段里面没有构造函数:

write this code in onActivityCreated inside your fragment not in constructor:

user_id =((ItemDetailActivity )getActivity()).getUser_id();

这是关于片段的生命周期 onActivityCreated 当片段成为活动的一部分,这是从哪儿getActivity()不返回第一个回调称为空

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

这篇关于Android的 - 如何从片段访问getter方法​​在父活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆