Задний план
У меня есть макет, в котором есть несколько представлений вверху, которые должны прокручиваться вместе с EditText под ними.
EditText занимает остальную часть пространства, столько места, сколько ему нужно.
Вот пример макета POC, который демонстрирует это (здесь использовались только 2 EditText):
<android.support.v4.widget.NestedScrollView android:id="@+id/nestedScrollView"
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent" android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
<EditText
android:id="@+id/titleEditText" android:layout_width="match_parent" android:layout_height="wrap_content"
android:ellipsize="end" android:hint="title" android:imeOptions="actionNext|flagNoExtractUi"
android:inputType="text|textAutoCorrect|textCapSentences" android:maxLines="1"
android:nextFocusDown="@id/contentEditText" android:nextFocusForward="@id/contentEditText"
android:scrollHorizontally="true" android:textColor="#2a2f3b" android:textColorHint="#a3a3a3"
android:textSize="21sp"/>
<EditText
android:id="@+id/contentEditText" android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="top" android:hint="content" android:background="@android:drawable/alert_light_frame"
android:imeOptions="actionDone|flagNoEnterAction|flagNoExtractUi" android:textSize="18sp"
android:inputType="textMultiLine|textAutoCorrect|textCapSentences"/>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
Я установил фоновую рамку, чтобы иметь визуальную индикацию размера EditText.
Проблема
Я нашел так много решений того, что я написал, но ни одно из них на самом деле не справляется с прокруткой.
То, что я всегда вижу, это как минимум одна из этих проблем:
- Невозможно прокрутить всю страницу (только EditText может прокручиваться, чего я пытаюсь избежать), поэтому больше не могу получить доступ к представлениям вверху.
- Когда я ввожу текст, курсор может выйти за пределы видимой области
- По мере того, как я набираю все больше и больше строк, он не прокручивает всю страницу. Только в самом EditText.
Что я пробовал
Я пробовал эти решения:
- Все из здесь, здесь, здесь, здесь. Может и больше, но я не следил...
- Я пробовал различные значения
windowSoftInputMode
в манифесте и пытался установитьisNestedScrollingEnabled
в NestedScrollView. - Пробовал различные конфигурации в XML, чтобы позволить EditText занимать столько места, сколько ему нужно, чтобы предотвратить его прокрутку внутри него.
Вопрос
Как я могу сделать так, чтобы нижний EditText занимал столько места, сколько ему нужно, и при этом иметь возможность прокручивать весь NestedScrollView без проблем с редактированием?
РЕДАКТИРОВАТЬ: поскольку исходное приложение немного сложнее, имея некоторые представления внизу (внутри того, что похоже на панель инструментов), которые автоматически скрываются, когда вы не находитесь в фокусе нижнего EditText , это сделало ответ, который я нашел не работать.
Кроме того, я случайно назначил награду за неправильный ответ, так что вот новая награда за более сложный POC. Вопрос остается прежним. NestedScrollView должен оставаться на том же месте, без прокрутки при фокусировании на нижнем EditText.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:orientation="vertical">
<View
android:layout_width="0dp" android:layout_height="0dp" android:focusable="true"
android:focusableInTouchMode="true"/>
<android.support.v4.widget.NestedScrollView
android:id="@+id/nestedScrollView" android:layout_width="match_parent" android:layout_height="0px"
android:layout_weight="1" android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
<EditText
android:id="@+id/titleEditText" android:layout_width="match_parent" android:layout_height="wrap_content"
android:ellipsize="end" android:hint="title" android:imeOptions="actionNext|flagNoExtractUi"
android:inputType="text|textAutoCorrect|textCapSentences" android:maxLines="1"
android:nextFocusDown="@id/contentEditText" android:nextFocusForward="@id/contentEditText"
android:scrollHorizontally="true" android:textColor="#2a2f3b" android:textColorHint="#a3a3a3"
android:textSize="21sp"/>
<android.support.constraint.ConstraintLayout
android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@android:drawable/alert_light_frame" android:clickable="true"
android:focusable="false">
<EditText
android:id="@+id/contentEditText" android:layout_width="match_parent"
android:layout_height="wrap_content" android:background="@null" android:gravity="top"
android:hint="content" android:imeOptions="actionDone|flagNoEnterAction|flagNoExtractUi"
android:inputType="textMultiLine|textAutoCorrect|textCapSentences" android:textSize="18sp"/>
</android.support.constraint.ConstraintLayout>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
<LinearLayout
android:layout_width="match_parent" android:layout_height="wrap_content" android:animateLayoutChanges="true"
android:orientation="vertical">
<LinearLayout
android:id="@+id/autoHideLayout" android:layout_width="match_parent" android:layout_height="wrap_content"
android:orientation="horizontal" android:visibility="gone" tools:visibility="visible">
<Button
android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="button"/>
<Button
android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="button2"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
container.setOnClickListener {
contentEditText.requestFocus()
contentEditText.setSelection(contentEditText.length())
}
contentEditText.setOnFocusChangeListener { view, hasFocus ->
autoHideLayout.visibility = if (hasFocus) View.VISIBLE else View.GONE
if (hasFocus)
nestedScrollView.scrollTo(0, 0)
}
}
}
The EditText takes the rest of the space, as much space as it needs
, вы имеете в виду, что он должен заполнять экран, а затем увеличиваться, если это необходимо? Или вы просто имеете в виду, что ему нужно позволить расти по мере необходимости, даже если он начинается меньше, чем заполняет экран? - person Ben P.   schedule 27.03.2018android:windowSoftInputMode="adjustResize"
установка этого в манифесте решила проблему. - person Sagar   schedule 28.03.2018