【问题标题】:Replace a fragment which has been added as tab of a tabhost替换已添加为选项卡主机选项卡的片段
【发布时间】:2013-01-24 14:20:36
【问题描述】:

我的 android 应用程序出现以下问题:

我有一个 TabHost,其中包含一些片段作为选项卡。这些片段已以编程方式添加。现在我想用另一个片段替换选项卡的内容。 我不知道如何实现这一目标。我found如何替换通过xml添加的片段,但这不是我想要实现的。

提前感谢您的任何建议。

编辑:请求的来源(仅相关部分,如果需要更多请告诉我)

我有一个方法来初始化标签主机并以编程方式添加标签/片段:

private void initialiseTabHost(Bundle args) {
    mTabHost = (TabHost)findViewById(android.R.id.tabhost);
    mTabHost.setup();

    addUserListTab(args);
    //methods to add other tabs


    mTabHost.setOnTabChangedListener(this);
}

private void addUserListTab(Bundle args){
    TabInfo tabInfo = null;
    LayoutParams tabIconParams = new LayoutParams(200, 110);
    tabIconParams.setMargins(0, 0, 0, 0);
    View userIndicator = LayoutInflater.from(this).inflate(R.layout.tab_indicator,mTabHost, false);
    ImageView userIcon = (ImageView) userIndicator.findViewById(R.id.tab_icon);  
    userIcon.setLayoutParams(tabIconParams);
    TabSpec specUser = mTabHost.newTabSpec("user");
    specUser.setIndicator(userIndicator);
    userIcon.setImageDrawable(getResources().getDrawable(R.drawable.selector_user));
    userIcon.setScaleType(ImageView.ScaleType.FIT_CENTER);

    AddTab(this, this.mTabHost, specUser, ( tabInfo = new TabInfo("user", ListUserFragment.class, args)));
    this.mapTabInfo.put(tabInfo.tag, tabInfo);

}
private static void AddTab(MainActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec, TabInfo tabInfo) {
    // Attach a Tab view factory to the spec
    tabSpec.setContent(activity.new TabFactory(activity));
    tabHost.addTab(tabSpec);
}

问题是我不明白如何替换我以编程方式添加到 tabhost 的 ListUserFragment。当我通过 tabhost 的容器时,如何指定当前四个选项卡中的哪个选项卡应该包含新片段,当然旧的应该被删除/隐藏。

【问题讨论】:

标签: android user-interface


【解决方案1】:

您需要获取FragmentManager 并开始FragmentTransaction 以用另一个Fragment 替换当前的Fragment

 getFragmentManager().beginTransaction().replace(R.id.container, new Fragment()).commit();

请务必同时阅读官方fragment guide.

【讨论】:

  • 这似乎不适用于替换以编程方式添加的片段。 R.id。 container 描述了旧片段的容器,自从我添加片段以来我没有它,它是以编程方式成为 TabHost 的父级。
  • 这适用于各种片段。把你的项目的来源发给我。
  • 我在 EDIT 中提供了源代码的相关部分。如果需要更多,请告诉我。我希望这足以说明我的问题。提前致谢
  • 在这种情况下替换片段“soriak”时应该使用什么id?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多