【问题标题】:FragmentTransaction replace entire screenFragmentTransaction 替换整个屏幕
【发布时间】:2013-03-21 14:28:19
【问题描述】:

我正在使用带有 FragmentStatePagedAdapter 的选项卡。下面的代码来自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;
  }

}

以及片段 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 代码...
  • 我在 xml 方面做得不多。你想看什么?
  • 想查看片段大小和传输位置...
  • 我添加了一些代码。希望以任何方式有所帮助。我以编程方式处理所有选项卡的内容,因为我发现它比 XML 更容易(也更灵活)。

标签: android android-fragments fragmenttransaction


【解决方案1】:

更新:如果您将 appcompat-v7 更新到 19.0.0. 或更高版本,则不再需要以下开关。请issue 59077了解更多信息。


我怀疑您使用的设备/模拟器运行的是 4.x(Ice Cream Sandwich,API 级别 14)之前的 Android 版本。我在使用片段事务时遇到了类似的覆盖问题。出现布局问题是因为与 Android 4.x 相比,Android 2.x 和 3.x 对 content view 的引用不同。请尝试更改您的代码:

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;
}

更多背景信息请见post of Shellum

【讨论】:

  • 当时我正在 Android 4.1.2 Galaxy S3 上调试应用程序。几个月前我已经离开了那个项目,但也许会再次挖掘整个事情来测试你的解决方案。我可能应该结束这个问题:/
猜你喜欢
  • 2021-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多