【问题标题】:Android: Adding fragments with android.R.id.contentAndroid:使用 android.R.id.content 添加片段
【发布时间】:2014-11-26 18:43:46
【问题描述】:

我正在尝试添加一个 Fragment 来填充 Activity 的空间(实际上是一个 ActionBarActivity,我使用的是 appcombat v7),如此处的 Android API 指南所示:https://developer.android.com/guide/topics/ui/actionbar.html#Tabs

所以活动类中的相关代码如下所示:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if(savedInstanceState == null) {
        SomeFragment fragment = new SomeFragment();
        getSupportFragmentManager()
            .beginTransaction()
            .add(android.R.id.content, fragment, fragment.getClass().getSimpleName())
            .commit();
    }
}

相当标准的东西。这编译没有任何抱怨..
问题是片段根本没有出现,好像活动没有附加视图。当我用 XML 中定义的另一个布局 id 替换 android.R.id.content 并将 setContentView 与布局资源一起使用时,片段正确显示。

不应该android.R.id.content 将片段添加到默认活动容器/视图中吗?
我需要为我的 Fragments 指定一个冗余的中间容器吗?

【问题讨论】:

    标签: android android-layout android-fragments android-view


    【解决方案1】:

    我在尝试将 PreferenceFragment 添加到 ActionBarActivity 时添加了同样的问题:片段根本不显示(它适用于简单的 Activity)。

    我通过定义一个具有单帧布局的虚拟布局 xml 文件解决了这个问题。然后我用我在onCreate 中的片段替换这个布局:

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        setContentView(R.layout.activity_settings);
    
        // Display the fragment as the main content.
        getFragmentManager().beginTransaction()
                .replace(R.id.settings_layout, new SettingsFragment())
                .commit();
    }
    

    activity_settings.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/settings_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </FrameLayout>
    

    【讨论】:

    • 感谢您的意见。虽然我使用了与您的答案类似的东西,但谷歌的代码无法按预期工作的事实仍然让我感到困惑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多