On Android, if you have a Spinner widget inside a Fragment, the Spinner could have white text on a white (or on a Light theme) background. The problem is most often due to an incorrect reference to the Context object.
The layout and code fragment are below.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="?android:windowBackground" tools:context=".MainFragment"> <Spinner android:id="@+id/spinner_filter" android:layout_width="match_parent" android:layout_height="wrap_content"/> </RelativeLayout> |
|
1 2 3 4 5 6 7 8 9 10 11 12 |
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = (View) inflater.inflate(R.layout.fragment_main,container,false); ... mFilterSpinner = (Spinner) view.findViewById(R.id.spinner_filter); mFilterAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),R.layout.fragment_main,mFilterList); mFilterSpinner.setAdapter(mFilterAdapter); ... } |
The problem is during the initialisation of the Adapter (in our case, it’s an ArrayAdapter) to be used with the Spinner. The context argument passed to the ArrayAdapter‘s constructor must be retrieved from getActivity() and not getActivity().getApplicationContext().
The Context from getActivity() will have the reference to the Resources.Theme object while the Context from getActivity().getApplicationContext() will not have any such reference.
The code in MainFragment.java should be changed as shown below.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = (View) inflater.inflate(R.layout.fragment_main,container,false); ... mFilterSpinner = (Spinner) view.findViewById(R.id.spinner_filter); mFilterAdapter = new ArrayAdapter<String>(getActivity(),R.layout.fragment_main,mFilterList); mFilterSpinner.setAdapter(mFilterAdapter); ... } |
Once the ArrayAdapter tied to the Spinner widget is initialised as shown above, the Spinner will inherit the correct background and foreground colors based on the selected theme.

