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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With