Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
563 views
in Technique[技术] by (71.8m points)

android - How to change color of Switch toggle button using state?

If I have a Switch component as follows;

           <Switch
                trackColor={{ false: '#e57373', true: '#81c784' }}
                thumbColor='gray'
                ios_backgroundColor="gray"
                onValueChange={(value) => this.setState({ toggle: value })}
                value={this.state.toggle}
            />

Can I change the color using a state value I have set e.g

 componentDidMount() {
    backgroundColor = this.props.dataBackgroundColor;
    primaryColor = this.props.dataPrimaryColor;

    this.setState({ background_color: backgroundColor })
    this.setState({ primary_color: primaryColor })

     console.log(this.state.primary_color) //#52A2C6
}

And then do something like;

 <Switch
                trackColor={{ false: '#e57373', true: this.state.primary_color }}
                thumbColor='gray'
                ios_backgroundColor="gray"
                onValueChange={(value) => this.setState({ toggle: value })}
                value={this.state.toggle}
            />

At the moment, no error is thrown but the color is not updated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Problem Solved.

Issue was with the props and how I am sharing the data between screens/components.

SettingScreen.js

const SettingsScreen = ({ route, navigation }) => {
const { background_color, primary_color } = route.params;
return (
    <View style={styles.container}>
        <Header />
        <Settings navigation={navigation} dataBackgroundColor={background_color} dataPrimaryColor={primary_color} />
    </View>
);

};

settings.js

  componentDidMount() {
    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
    backgroundColor = this.props.dataBackgroundColor;
    primaryColor = this.props.dataPrimaryColor;
    this.setState({ background_color: backgroundColor })
    this.setState({ primary_color: primaryColor })

    console.log(this.state.primary_color)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...