У меня ограничено пространство в одном из моих представлений, и я пытаюсь реализовать представление с прокруткой, которое может помочь решить проблему ограниченного пространства.Однако, когда я пытаюсь реализовать представление прокрутки, оно портит клавиатуру, каждый раз, когда я сейчас пытаюсь отредактировать EditText, это заставляет элементы в представлении перемещаться вверх с помощью клавиатуры.
Есть ли другие решенияили обходные пути, которые я могу попытаться реализовать?
Я пробовал решение на Переместить макеты вверх, когда отображается программная клавиатура? , которые предлагают добавить следующий код в манифест android:windowSoftInputMode="stateHidden|adjustResize
который не позволяет клавиатуре подпрыгивать во время выполнения.
Я также пытался установить гравитацию вида прокрутки и использовать различные примеры компоновок: линейные, с ограничениями, относительные раскладки.Я попытался создать собственный класс клавиатуры и реализовать его, установив его в соответствующем классе активности представления (Не мой код, но попытался реализовать его)
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
Это дает статическую ошибку члена, которую я не могуне знаю, как решить.
Однако ни один из них не решил проблему.
Мой текущий файл макета, который вызывает ошибку.
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:focusable="true"
android:focusableInTouchMode="true"
android:id="@+id/main_layout1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/freq_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Freq"
android:textSize="14sp" />
<EditText
android:id="@+id/freq"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:digits="0123456789.,"
android:inputType="numberDecimal"
android:textAlignment="center"
android:textColor="@color/black" />
<Spinner
android:id="@+id/spinner_r1_unit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:tooltipText="unit"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="5dp">
<TextView
android:id="@+id/duty_cycle_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/duty_cycle"
android:textSize="14sp"
android:layout_marginLeft="5dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/duty_cycle_percentage"
android:layout_marginLeft="5dp"
android:text="50%"/>
</LinearLayout>
<SeekBar
android:id="@+id/seekBar"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:max="100"
android:progress="50" />
<android.support.v7.widget.AppCompatButton
android:layout_width="100dp"
android:layout_below="@id/main_layout1"
android:layout_height="wrap_content"
android:text="Design"
android:layout_marginLeft="30dp"
android:id="@+id/button_design"
android:layout_marginTop="10dp"
android:background="@drawable/white_rounded_button"
/>
<ScrollView
android:layout_width="200dp"
android:layout_height="100dp"
>
</ScrollView>
</LinearLayout>
</merge>
Если я удаляюпредставление с прокруткой решает проблему, однако мне нужно добавить представление с прокруткой, поскольку этот XML-файл используется в качестве фрагмента в другом XML-файле, где пространство очень ограничено.
Есть ли другие возможные способы реализации представления с прокруткой?Есть ли какое-либо хорошее объяснение тому, почему это представление с прокруткой вызывает эту ошибку, и учитывая проблему с пространством, какие есть другие альтернативы, которые я могу принять во внимание, которые могут привести к результатам, аналогичным таковым для представления с прокруткой, без возникновения ошибки клавиатуры?