getParentFragment API 16 [英] getParentFragment API 16

查看:277
本文介绍了getParentFragment API 16的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都知道 getParentFragment 片段在17 API介绍。对

那么,如果我们想获得父母片段API 16及以下(考虑到我使用本机片段与支持 FragmentStatePagerAdapter 和嵌套的片段也没问题)

有没有比我更好的办法?

在父:

 公共类ParentFragment扩展片段{

公共静态ParentFragment StaticThis;
...

@覆盖
公共查看onCreateView(LayoutInflater吹气,父母的ViewGroup,捆绑savedInstanceState){
super.onCreate(savedInstanceState);

StaticThis =这一点;

...
}
 

在子:

 如果(Build.VERSION.SDK_INT> = Build.VERSION_ codeS.JELLY_BEAN_MR1)
         parentFragment =(ParentFragment)getParentFragment();
其他
         parentFragment = ParentFragment.StaticThis;
 

解决方案

根据您的评论,如果你想从项目顶嘴你的 ViewPager (我M猜测这是一个片段)的容器中的 ViewPager 这是一个 FragmentActivity 则可以使用一个接口。

(1)无论是declar在片段本身或作为一个单独的文件接口 (2)初始化在你的片段的onAttach方法inteface。例如

 私人SomeInterface等等;

 @覆盖
 公共无效onAttach(活动活动){
    等等=(SomeInterface)的活动;
 }
 

(3)实现在接口的 FragmentActivity

您可以再从你的片段回调至 FragmentActivity 。从那里,你可以调用任何你想在 FragmentActivity 或者,如果你得到一个引用任何被加载到其他片段你的 ViewPager方法,称之为片段内的任何公共方法。这可以让你没有内存泄漏碎片和它们的容器之间的通信。

We all know getParentFragment of Fragment is introduced in API 17.

So what if we want to get parent fragment in API 16 and below (Considering that I use native Fragment with support FragmentStatePagerAdapter and have no problem with nested fragments)

Is there any better way than mine?

In parent:

public class ParentFragment extends Fragment {

public static ParentFragment StaticThis;
...

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

StaticThis = this;

...
}

In child:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
         parentFragment = (ParentFragment) getParentFragment();
else
         parentFragment = ParentFragment.StaticThis;

解决方案

Based on your comment if you want to talk back from the "items" in your ViewPager (I'm guessing this is a Fragment) to the container of the ViewPager which is a FragmentActivity you can use an interface.

(1) Either declar the interface in the Fragment itself or as a separate file (2) "Initialize" the inteface in your fragment's onAttach method. For example

 private SomeInterface blah;

 @Override
 public void onAttach(Activity activity){
    blah = (SomeInterface) activity;
 }

(3) Implement the interface in your FragmentActivity.

You can then callback to the FragmentActivity from your Fragment. From there you can call any method you want within the FragmentActivity or, if you get a reference to any of the other fragments that are loaded into your ViewPager, call any public method within that Fragment. This allows you to communicate between fragments and their container without a memory leak.

这篇关于getParentFragment API 16的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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