Android Fragment does not respect match_parent as height

davidcesarino picture davidcesarino · Oct 28, 2011 · Viewed 32.8k times · Source

Sorry for the huge code dump, but I'm truly lost.

MyActivity.java onCreate:

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_singlepane_empty);
mFragment = new PlacesFragment();
getSupportFragmentManager().beginTransaction()
                    .add(R.id.root_container, mFragment)
                    .commit();

PlacesFragment.java onCreateView:

mRootView = (ViewGroup) inflater.inflate(R.layout.list_content, null);
return mRootView;

Notes: mRootView is a ViewGroup global, no problem about it, I believe. PlacesFragment is a ListFragment.

Layouts:

activity_singlepane_empty.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root_container"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00f">
    <include layout="@layout/actionbar"/>

    <!-- FRAGMENTS COME HERE! See match_parent above -->

</LinearLayout>

list_content.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listContainer"
        android:background="#990"
        >
    
        <ListView android:id="@android:id/list"
                android:layout_width="match_parent" 
                android:layout_height="match_parent"
                android:drawSelectorOnTop="false" />
        
        <TextView android:id="@id/android:empty"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:gravity="center"
                android:textAppearance="?android:attr/textAppearanceMedium" 
                android:text="@string/no_data_suggest_connection"/>

</FrameLayout>

Problem: as you can see, the expected behavior would be to have the empty TextView above to appear centered on the screen. On the design preview in Eclipse, it is OK. Only when added to root_view as a fragment the FrameLayout won't fill the whole screen.

root_container is blue, and FrameLayout is yellowish, see below for debug purposes. Shouldn't the yellow pane fill the whole screen?!?!?!?

enter image description here

Answer

Norman picture Norman · Mar 12, 2012

I had the same problem and think it happens when you inflate the layout in the Fragment's onCreateView with null, like you did here:

mRootView = (ViewGroup) inflater.inflate(R.layout.list_content, null);

Instead you have to do this:

mRootView = (ViewGroup) inflater.inflate(R.layout.list_content,container, false);

Where container is the Viewgroup. At least, that solved the problem for me.