编程替换片段 [英] Replace a fragment programmatically

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

问题描述

我有三个片段,如下面的图。我已经加入这三个片段的LinearLayout使用.xml文件和我的发射活动开始时,我使用的setContentView加载的.xml布局。

我有fragment2一些控制。点击任何一个加载 fragment4编程方式使用FragmentTransaction和commit方法。这个片段被添加到屏幕,但问题是该prgrammatically加入fragment4取整个屏幕区域。可能是什么问题

注:在任何项目点击在f2我想更换新的片段F4只有F2。请记住我已经加入F1,F2,F3通过XML布局文件和编程方式添加新片段F4。

输入图像的描述在这里

I have three fragments as shown in below figure. I have added all these three fragments in LinearLayout using .xml file and when my launcher activity starts I load that .xml layout using setContentView.

I have some controls on fragment2. Clicking on any one loads the fragment4 programmatically using FragmentTransaction and commit method. This fragments is added to the screen but the problem is the prgrammatically added fragment4 take the whole screen area. What can be the problem?

Note: On any item click at f2 I want to replace only f2 with new fragment f4. Keep in mind I have added f1, f2, f3 through xml layout file and adding new fragment f4 programmatically.

推荐答案

您应该随时添加,删除和编程取代您的片段。因此我建议你使用的容器,如更换的FrameLayout您的F-1,F-2和F-3的片段。

You should always add, remove and replace your fragments programatically. As such I suggest you replace your F-1, F-2 and F-3 fragments with containers such as FrameLayout.

基本上,而不是有一个<片段/> 元素作为F-1,你让它<的FrameLayout /> 元素。然后你在FragmentActivity的onCreate执行片段交易:

Basically instead of having a <fragment/> element as F-1 you make it a <FrameLayout/> element. Then you perform a fragment transaction in your FragmentActivity's onCreate:

Fragment1 f1 = new Fragment1();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.f1_container, f1); // f1_container is your FrameLayout container
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();  

现在,假设你已经为F-1,F-2和F-3做到了这一点。然后,再次做同样的事情在更换F2与F4的 OnClickListener

Now, Suppose you have done this for F-1, F-2 and F-3. You then replace f2 with f4 by doing the same thing again in your OnClickListener:

public void onClick(View v) {
    Fragment4 f4 = new Fragment4();
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.f2_container, f4); // f2_container is your FrameLayout container
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    ft.addToBackStack(null);
    ft.commit();   
}

这篇关于编程替换片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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