React Native(Expo)中如何让AdMob广告不随键盘上移
让AdMob广告固定在屏幕底部(不受键盘弹出影响)
核心思路
通过绝对定位固定广告位置+调整Android键盘行为,解决广告随键盘上移的问题,同时保证页面内容可正常访问。
步骤1:修改页面布局与样式
调整登录页面的结构,用绝对定位把广告钉在屏幕底部,同时给滚动视图添加底部内边距,避免内容被广告遮挡:
render() { return ( <View style={styles.container}> {this.showModal()} {/* 滚动视图占满上方剩余空间,底部留空避免被广告挡住 */} <ScrollView style={styles.scrollView}> <BTex style={styles.title}>Login</BTex> <Tex style={styles.sub}>Please sign in to continue</Tex> <Tex style={styles.label}>Email</Tex> <TextInput style={styles.input} placeholder="example@email.com" placeholderTextColor="#BBBBBB" onChangeText={(text) => { this.setState({ email: text }); }} keyboardType="email-address" keyboardAppearance="dark" autoCapitalize="none" /> <Tex style={[styles.label, { marginTop: RFValue(25) }]}>Password</Tex> <TextInput style={styles.input} placeholder="VerySecurePassword123" placeholderTextColor="#BBBBBB" onChangeText={(text) => { this.setState({ password: text }); }} keyboardType="default" keyboardAppearance="dark" secureTextEntry={true} autoCapitalize="none" /> <TouchableOpacity style={styles.loginCTA} onPress={() => this.login()} > <Tex style={styles.buttonText}>Login</Tex> </TouchableOpacity> <TouchableOpacity style={{ alignSelf: "center", marginTop: RFValue(15), marginBottom: RFValue(7), }} onPress={() => this.setState({ isModalVisible: true })} > <Tex style={{ fontSize: RFValue(15) }}> Create an account instead </Tex> </TouchableOpacity> </ScrollView> {/* 绝对定位固定广告在底部 */} <View style={styles.adContainer}> <Advert /> </View> </View> ); } // 对应样式 const styles = StyleSheet.create({ container: { flex: 1, // 保留你原有的背景色、padding等样式 }, scrollView: { flex: 1, // 底部内边距设为广告实际高度(比如50,根据你的广告调整) paddingBottom: 50, // 保留原有的其他样式 }, adContainer: { position: 'absolute', bottom: 0, left: 0, right: 0, // 若广告自带margin,可在这里调整 }, // 保留你原有的title、input等样式 });
步骤2:配置Android键盘行为
打开Android项目的android/app/src/main/AndroidManifest.xml,找到MainActivity标签,修改windowSoftInputMode为adjustPan,让键盘弹出时平移页面而非压缩布局,确保广告不随之上移:
<activity android:name=".MainActivity" android:label="@string/app_name" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode" android:launchMode="singleTask" android:windowSoftInputMode="adjustPan" <!-- 修改这一行 --> android:exported="true">
步骤3:iOS端适配(可选)
iOS默认键盘会压缩布局,此时用KeyboardAvoidingView包裹滚动视图,保证输入区域不被键盘遮挡,同时广告仍固定在底部:
import { KeyboardAvoidingView, Platform } from 'react-native'; render() { return ( <View style={styles.container}> {this.showModal()} <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : 'height'} style={{ flex: 1 }} > <ScrollView style={styles.scrollView}> {/* 原有滚动视图内容 */} </ScrollView> </KeyboardAvoidingView> <View style={styles.adContainer}> <Advert /> </View> </View> ); }
内容的提问来源于stack exchange,提问作者Lakshya Agarwal
相关产品推荐
相关产品推荐

