片段事务替换整个屏幕

3

我正在使用FragmentStatePagerAdapter来处理选项卡。下面的代码是在onOptionsItemSelected(MenuItem item)方法中:

case R.id.menu_help:
  System.out.println("Pressin' da help button!");
  FragmentManager mananger = getSupportFragmentManager();
  android.support.v4.app.FragmentTransaction trans = mananger.beginTransaction();
  trans.replace(android.R.id.content, new HelpFragment());
  trans.addToBackStack(null);
  trans.commit();
  break;

android.R.id.content 只会替换操作栏下面的视图(并将其覆盖在选项卡片段上方)。是否有一种简单的方式能够用片段替换整个屏幕呢(难道不应该有其他系统资源来实现吗?)而不必为此创建一个新活动吗?或者创建一个新活动实际上更好吗?

提前感谢您的帮助。

容器布局(从 MainActivity 启动):

<android.support.v4.view.ViewPager
    android:id="@+id/masterViewPager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

我猜这是HelpFragment的类:

public class HelpFragment extends Fragment {

  private View view;

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle states) {
    view = inflater.inflate(R.layout.layout_help_screen, container, false);

    return view;
  }

}

并且Fragment XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/nothing" />

</LinearLayout>

展示你的 XML 代码... - Developer
我在XML方面没有做太多的工作。你想看什么? - AreusAstarte
想要查看片段大小和传输位置... - Developer
我添加了一些代码。希望这有所帮助。我正在以编程方式处理所有选项卡的内容,因为我发现这比在XML中更容易(也更灵活)。 - AreusAstarte
1个回答

0

更新:如果您将appcompat-v7更新到19.0.0或更高版本,则不再需要下面的开关。请参阅问题59077获取更多信息。


我怀疑您正在使用运行Android 4.x(Ice Cream Sandwich,API级别14)之前的设备/模拟器。当我使用片段事务时,我遇到了类似的覆盖问题。布局问题发生是因为在Android 2.x和3.x上与Android 4.x不同地引用了内容视图。请尝试将您的代码从以下更改:

trans.replace(android.R.id.content, new HelpFragment());

至:

trans.replace(getContentViewCompat(), new HelpFragment());

...

public static int getContentViewCompat() {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH ?
               android.R.id.content : R.id.action_bar_activity_content;
}

更多背景信息可以在Shellum的帖子中找到。


我当时正在一个Android 4.1.2 Galaxy S3上调试应用程序。几个月前我已经离开了那个项目,但也许会再次挖出整个东西来测试你的解决方案。我应该关闭这个问题 :/ - AreusAstarte

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接