Панель инструментов Android перемещается вверх, когда появляется клавиатура

Я создаю экран пользовательского интерфейса, основанный на чатах, где у меня есть панель инструментов и recyclerview для сообщений чата, и ответьте макет msg.

Всякий раз, когда edittext получает фокус, он перемещается вверх по панели инструментов. Вместо этого я хотел бы изменить размер recyclerview.

некоторые из ответов stackoverflow предлагают разместить пустой scrollview под панелью инструментов , но это не сработало.

        <activity
            android:name=".PostMessageActivity"
            android:label="@string/title_activity_post_message"
            android:windowSoftInputMode="stateVisible|adjustResize"
            >
        </activity>

Я устанавливаю windowSoftInputMode в stateVisible|adjustPan в файле манифеста.

<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"
tools:context="com.pasonet.yokibu.PostMessageActivity"
>
<include
    android:id="@+id/toolbar_home"
    layout="@layout/toolbar_home"
    android:elevation="5dp"
    />

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</ScrollView>


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/toolbar_home"
    android:orientation="vertical"
    android:layout_above="@+id/add_post_layout"
    >
    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/post_msg_recyclerview"
        >
    </android.support.v7.widget.RecyclerView>


</LinearLayout>

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:padding="5dp"
    android:id="@+id/add_post_layout"
    android:background="#ffffff"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:elevation="5dp"
    android:layout_margin="0pt"
   >

    <EditText
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:id="@+id/messageText"
        android:layout_gravity="bottom"
        android:layout_weight="1"
        android:maxLines="4"
        android:scrollbars="vertical"
        android:background="@color/trasnperant"
        android:hint="Type your message"
        android:layout_marginBottom="4dp"
        />
    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_send_black_36dp"
        android:id="@+id/sendButton"
        android:background="@drawable/abc_btn_default_mtrl_shape"
        android:onClick="addPost"
        />
</LinearLayout>

введите описание изображения здесь

Ответы

Ответ 1

Проблема заключалась в том, что я использовал <item name="android:windowTranslucentStatus">true</item> в styles.xml

Чтобы включить adjustResize добавить android:fitsSystemWindows="true" в родительский макет вашего мероприятия

Ответ 2

Или добавьте эту строку в манифест. android:windowSoftInputMode="adjustResize"

Ответ 3

Если вы не хотите, чтобы ваш Toolbar был нажат, вы не должны использовать adjustPan. Использовать adjustResize без каких-либо других вещей (без добавления дополнительных Views) должно быть достаточно.

Ответ 4

В моем случае мое приложение по умолчанию использовало компоновку координатора для корневого элемента. Даже то, что было описано выше, не решает мою проблему. Затем я сделал следующее:

  • Изменен макет корня из макета координатора в RelativeLayout
  • Включено android:fitsSystemWindows="true" в корневую компоновку
  • Включен android:windowSoftInputMode="adjustResize|stateAlwaysHidden" в тег манифеста активности.

Ответ 5

Вы должны добавить android: fitsSystemWindows = "true" в корневой макет панели инструментов. Если вы добавите его в макет родительской активности, на панели инструментов появится странная строка (со статусной строкой).

Ответ 6

<include
    android:id="@+id/toolbar_home"
    layout="@layout/toolbar_home"
    android:elevation="5dp"
android:layout_alignParentTop="true"
    />

Ответ 7

попробуйте это,

android:windowSoftInputMode="adjustPan"

в вашем manifest.xml в теге активности.

Ответ 8

Используя android:windowSoftInputMode="adjustNothing" в действии в манифесте, работал у меня.

Ответ 9

Пожалуйста, проверьте WindowsSoftInputMode в Android Manifest попробуйте установить AdjustResize или AdjsutPan

Ответ 10

Я использую CoordinatorLayout в качестве корневого макета для панели инструментов. У меня была такая же проблема, но она была решена, установив панель инструментов:

app:layout_scrollFlags="enterAlways" 

вместо:

app:layout_scrollFlags="scroll|enterAlways"

и добавив:

android:windowSoftInputMode="adjustNothing"

в действии в манифесте.

Ответ 11

Я пробовал много способов удержать панель инструментов, но не изменяя размеры или сжатие макета с помощью android: windowSoftInputMode = "adjustResize", это не правильно.

Это возможно только по схеме Координатора,

<android.support.design.widget.CoordinatorLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.design.widget.CollapsingToolbarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar 
           xmlns:android="http://schemas.android.com/apk/res/android"
           xmlns:ripple="http://schemas.android.com/apk/res-auto"
           android:id="@+id/tv_toolbar"
           android:layout_width="match_parent"
           android:layout_height="50dp"
           android:background="#fff"
           ripple:contentInsetStart="0dp">
        </android.support.v7.widget.Toolbar>

    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>

<ScrollView
    android:id="@+id/coordinate_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:marginTop="56dp">
</ScrollView>

Храните структуру как

 Coordinator layout
  |-->Toolbar    (android:id="@+id/toolbar")
  |-->ScrollView (android:layout_below="@id/toolbar")
   |-->Child
   |-->Child
   |-->Child

Ответ 12

Here is the solution for this fix
- android:windowSoftInputMode="adjustResize" in Manifest File
- Make a class "CommentKeyBoardFix.Java" and copy and paste the below code.

public class CommentKeyBoardFix
{
private View mChildOfContent;
private int usableHeightPrevious;
private FrameLayout.LayoutParams frameLayoutParams;
private Rect contentAreaOfWindowBounds = new Rect();

public CommentKeyBoardFix(Activity activity)
{
    FrameLayout content = activity.findViewById(android.R.id.content);
    mChildOfContent = content.getChildAt(0);
    mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(this::possiblyResizeChildOfContent);
    frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams();
}

private void possiblyResizeChildOfContent()
{
    int usableHeightNow = computeUsableHeight();
    if (usableHeightNow != usableHeightPrevious)
    {
        int heightDifference = 0;
        if (heightDifference > (usableHeightNow /4))
        {
            // keyboard probably just became visible
            frameLayoutParams.height = usableHeightNow - heightDifference;
        }
        else
        {
            // keyboard probably just became hidden
            frameLayoutParams.height = usableHeightNow;
        }
        mChildOfContent.layout(contentAreaOfWindowBounds.left, contentAreaOfWindowBounds.top, contentAreaOfWindowBounds.right, contentAreaOfWindowBounds.bottom);
        mChildOfContent.requestLayout();
        usableHeightPrevious = usableHeightNow;
    }
}

private int computeUsableHeight()
{
    mChildOfContent.getWindowVisibleDisplayFrame(contentAreaOfWindowBounds);
    return contentAreaOfWindowBounds.height();
}
}

And then call this class in your Activity or Fragment
setContentView(R.layout.your_comments_layout)
CommentKeyBoardFix(this) ---> For Kotlin
or
new CommentKeyBoardFix(this) ---> For Java