最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - I am having issues on adjusting layout on android when soft keyboard appears on screen in react-native - Stack Over

programmeradmin4浏览0评论

I am working on a react-native app and using "react-native": "0.73.6", and I am facing some UI issues when the keyboard appears on the screen in my MessageInboxScreen. Below is the code for the screen:

import React, { useEffect, useRef, useState } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Image, TextInput, ActivityIndicator, FlatList, Alert, SafeAreaView, } from 'react-native';
import { COLORS } from '../../themes/palette';
import MainCommonHeader from '../../components/headers/MainCommonHeader';
import { moderateScale, scale, verticalScale } from 'react-native-size-matters/extend';

const NewInboxScreen = ({ route, navigation }) => {
    const { data } = route.params || {};
    const [filteredMessages, setFilteredMessages] = useState([]);
    const [loading, setLoading] = useState(true);
    const [messageBody, setMessageBody] = useState('');
    const [sending, setSending] = useState(false); // Track sending state
    const conversationNumber = data;

    const sendSMS = async () => {
        if (!messageBody.trim()) {
            Alert.alert('Error', 'Message body cannot be empty!');
            return;
        }
        setSending(true);
        console.log(`Message sent to +${conversationNumber}:`, messageBody);

        try {
                setFilteredMessages((prevMessages) => [...prevMessages, newMessage]);
                setMessageBody(''); // Clear the TextInput
                setSending(false);
        } catch (error) {
            console.error('Error sending SMS:', error);
            Alert.alert('Error', 'Failed to send SMS');
        } finally {
            setSending(false);
        }
    };

    const renderItem = ({ item }) => {
        const isOutGoing = item.sb === 'out';
        return (
            <TouchableOpacity disabled style={{
                paddingVertical: verticalScale(12),
                paddingHorizontal: scale(12),
                borderWidth: 1,
                width: '100%',
                borderColor: COLORS.SOFT_GREY,
                backgroundColor: isOutGoing ? '#CCDBFD26' : COLORS.WHITE,
                borderRadius: scale(8),
                marginBottom: verticalScale(10),
                alignSelf: item.direction === 'inbound' ? 'flex-start' : 'flex-end',
            }}>
                <View style={{ flex: 1, flexDirection: 'row', alignItems: 'flex-start' }}>
                    {!isOutGoing && <View style={{ width: scale(40), height: scale(40), borderRadius: scale(20), backgroundColor: COLORS.DARK_FADE_40, marginRight: scale(20) }} />}

                    <Text style={{ fontFamily: 'BlinkerRegular', color: COLORS.DARK, fontSize: moderateScale(16, 0.5), textAlign: 'left', flexShrink: 1 }}>{item.mb}</Text>
                </View>
                <Text style={{ fontFamily: 'BlinkerLight', fontSize: moderateScale(15, 0.5), color: COLORS.DARK_GRAY, textAlign: 'right' }}>{new Date(item.sdt).toLocaleString()}</Text>
            </TouchableOpacity>
        );
    };

    return (
        <SafeAreaView style={styles.container}>
            <MainCommonHeader
                leftText="SMS"
                leftSubText={`+${conversationNumber}`}
                goBackIcon="left"
                leftAction={() => navigation.goBack()}
            />
            <View style={styles.subContainer}>
                {loading ? (
                    <ActivityIndicator size="large" color="#0000ff" />
                ) : (
                    <FlatList
                        data={filteredMessages}
                        renderItem={renderItem}
                        keyExtractor={(item, index) => index.toString()}  // Unique key for each item
                        onContentSizeChange={() => flatListRef.current?.scrollToEnd({ animated: true })}
                        onLayout={() => flatListRef.current?.scrollToEnd({ animated: true })} // Ensure scrolling on layout
                    />
                )}

            </View>
            <View style={{ width: '100%', height: verticalScale(185), paddingHorizontal: scale(16), paddingVertical: verticalScale(12), alignSelf: 'center' }}>
                <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center', backgroundColor: COLORS.WHITE, borderRadius: scale(8), borderColor: COLORS.SOFT_GREY, borderWidth: 1, paddingHorizontal: scale(12) }}>
                    <TextInput
                        style={{ flex: 1, height: '100%', paddingHorizontal: scale(16), color: COLORS.DARK, verticalAlign: 'top' }}
                        placeholder="Write new message"
                        placeholderTextColor={COLORS.DARK_FADE_40}
                        multiline
                        value={messageBody}
                        onChangeText={setMessageBody}
                        editable={!sending}  // Disable input when sending
                    />
                    <TouchableOpacity onPress={() => sendSMS()}>
                        <Image source={require('../../assets/images/send.png')} style={{ width: scale(27), height: scale(27) }} />
                    </TouchableOpacity>
                </View>
            </View>
        </SafeAreaView>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: COLORS.OFFWHITE,
    },
    subContainer: {
        flex: 1,
        paddingHorizontal: scale(16),
        paddingVertical: verticalScale(16),
    },
    itemContainer: {
        padding: 16,
        borderBottomWidth: 1,
        borderColor: '#ccc',
    },
    text: {
        fontSize: 16,
        marginVertical: 2,
        color: COLORS.DARK,
    },
});

export default NewInboxScreen;

Now in this screen when the keyboard appears here then the header or say screen layout automatically gets resized. You can see the below screenshots.

  1. This is the actual layout of the screen before opening keyboard.

  2. This is the layout of the screen after opening keyboard.

you can see the header height gets reduced on opening the keyboard. Also in my in AndroidManifest.xml I have android:windowSoftInputMode="adjustResize" and when I change it to android:windowSoftInputMode="adjustPan" then when the keyboard appears my UI looks like:

Here you can see that when keyboard appears it everything is pushed up the header also and the input-box is under the keyboard. I also tried using KeyboardAvoidingView but it is not working as expected. So please help here how can I solve this issue. Thank you.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论