Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Adding fragments with android.R.id.content

I'm trying to add a Fragment to fill up an Activity's space (actually an ActionBarActivity, i'm using appcombat v7) as shown in the Android API guides here: https://developer.android.com/guide/topics/ui/actionbar.html#Tabs

So the relevant code inside the activity class looks something like this:

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

Pretty standard stuff.This compiles without any complaints..
The problem is that the Fragment doesn't appear at all, as if the Activity had no views attached.When i replace android.R.id.content with another layout id defined in XML and use setContentView with the layout resource the fragment appears correctly.

Shouldn't android.R.id.content add the fragment to a default activity container/view?
Do i need to specify a redundant in-between container for my Fragments?

like image 831
Heliosophist Avatar asked Nov 01 '22 13:11

Heliosophist


1 Answers

I add the same problem when trying to add a PreferenceFragment to an ActionBarActivity : the fragment does not show at all (it works on a simple Activity).

I solved it by defining a dummy layout xml file, with a single frame layout. Then I replace this layout with my fragment in 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>
like image 141
Pierre Rust Avatar answered Nov 11 '22 10:11

Pierre Rust