Home > database >  How to disable default scroll behavior of an EditText?
How to disable default scroll behavior of an EditText?

Time:04-06

The title of question might look similar to other questions but It's not. I have several strange problem that I am not being able to solve it.

I have a xml layout and the structure of that layout looks like below.

LinearLayout
     |
  ScrollView
        |
     LinearLayout
           |
         TextView
         EditText(multiLine)

The xml:-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fillViewport="true">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Large Text"/>

            <EditText
                android:layout_width="match_parent"
                android:inputType="textMultiLine"
                android:layout_height="match_parent"/>

        </LinearLayout>

    </ScrollView>

</LinearLayout>

Now let's discuss about problem. If I keep adding new line to the editText, the editText itself scroll and the TextView which is located above EditText is not scroll. But what I want is EditText not to scroll and leave the job for scrollView so that the textView which is loacated above EditText also scroll along with EditText when new Line is added.

ScrollView behave ok when I press back(usually when the editText is not focused anymore). Setting to

<ScrollView
    ...
    layout_height="wrap_content">

fix the problem but the desired height then compromised. Same thing happen with Horizontal scrollView also.

Is there any way to solve this problem ? Detailed Answer will be helpful.

CodePudding user response:

Set your EditText's height to wrap_content so it expands instead of scrolling. Set your LinearLayout's height to wrap_content so it's the size of its contents, i.e. the TextView and EditText.

The ScrollView should be whatever height you want for your "window" into the contents layout, the LinearLayout that moves up and down "behind" the ScrollView.

The scrolling happens if that contents layout is too big to display in the visible ScrollView, which is why that contents layout should always be wrap_content (the size of the contents) and never match_parent (the size of the scroll view "window"). If the contents are always the same size as the scroll view, they'll never need to scroll, right?

  • Related