Home » Android » How to style the react-native picker using android styles.xml?

How to style the react-native picker using android styles.xml?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I wanted to know how to set the fontFamily. How to set the color & background color on the Picker.items?

<Picker
   style={styles.picker} // cannot set fontFamily here
   selectedValue={this.state.selected2}
   onValueChange={this.onValueChange.bind(this, 'selected2')}
   mode="dropdown">
   <Item label="hello" value="key0" /> // cannot set backgroundColor here
   <Item label="world" value="key1" />
</Picker>

I posted this on Github and got the answer that only some of the attributes can be set in React Native via the style but some of the more core elements of the picker (like the font used) is driven by native Android. It needs to be done via native android using styles.xml etc.

Unfortunately I am not a native android developer so I have trouble understanding the solution. I added the following snippet to /res/values/styles.xml but text color or background of the popup didn’t change.

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
    </style>
    <style name="SpinnerItem">
        <item name="android:textColor">#ffffff</item>
        <item name="android:background">#993399</item>
    </style>
    <style name="SpinnerDropDownItem">
        <item name="android:textColor">#ffffff</item>
        <item name="android:background">#993399</item>
    </style>
</resources>

What other changes do I need to make? How to set the fontFamily?

How to&Answers:

That’s because you need to declare the styles inside your AppTheme

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="android:spinnerItemStyle">@style/SpinnerItem</item>
        <item name="android:spinnerDropDownItemStyle">@style/SpinnerDropDownItem</item>
    </style>
    <style name="SpinnerItem">
        <item name="android:textColor">#ffffff</item>
        <item name="android:background">#993399</item>
    </style>
    <style name="SpinnerDropDownItem">
        <item name="android:textColor">#ffffff</item>
        <item name="android:background">#993399</item>
    </style>
</resources>

That’s it 🙂