Android: Change Background Color of Fragment

Brandon Ling picture Brandon Ling · Jul 27, 2012 · Viewed 67k times · Source

I tried changing the background color of a fragment, but a small problem occurred.

public class MainActivity extends FragmentActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

So, shown above is the code I had for my main class that calls the XML file for the fragment.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <fragment
        android:id="@+id/fragment1"
        android:name="com.northreal.practice.FirstFragment"
        android:layout_width="0dip"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#CBA" />

</LinearLayout>

Above is the main.xml layout that is called by the main class (MainActivity).

public class FirstFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.main, parent, false);
    }
}

Above the XML file with the fragment calls this class.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
     >

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="BLAHHHH"
        android:layout_gravity="center_vertical" />

</LinearLayout>

This layout above is inflated by the class FirstFragment

So, why doesn't this actually change the color of the background of my fragment?

Answer

Adam picture Adam · Apr 11, 2013

Fragments don't inherit from View and thus don't have a set background method.

Any easy fix is to just grab the root view of fragment and set its background

fragment.getView().setBackgroundColor(Color.WHITE);