我们都知道 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.
相关推荐
最新文章