Android:在afterTextChanged中滚动不起作用

时间:2017-06-11 21:29:40

标签: android scroll android-edittext textwatcher

我有一个ImageView,下面是EditText。我希望能够在查看ImageView时写入EditText。此时,EditText不可见。有没有人知道如何实现这一目标? 我用TextWatcher尝试过,但是afterTextChanged中的scrollTo不起作用。

myImageView.setImageBitmap(myImageBitmap);
TextWatcher textWatcher = new TextWatcher() {
    int xBefore;
    int yBefore;

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        yBefore = myScrollView.getScrollY();
        xBefore = myScrollView.getScrollX();
    }

    @Override
    public void afterTextChanged(Editable s) {
        myScrollView.scrollTo(xBefore, yBefore);
    }
};
myEditText.addTextChangedListener(textWatcher);

xml如下所示:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/myScrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<LinearLayout
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="ch.ethz.somr.smartphonebattle.FastestCameraActivity"
    android:orientation="vertical">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/myImageView"
        android:scaleType="fitStart"
        android:adjustViewBounds="true"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:id="@+id/container_input">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/myEditText"
            android:inputType="number"
            android:hint="@string/my_hint"/>

    </LinearLayout>

</LinearLayout>
</ScrollView>

1 个答案:

答案 0 :(得分:0)

我发现如果你在afterTextChanged中等待很短的时间,我的代码就可以工作了,就像它有效一样:

Runnable myRunnable = new Runnable() {
    @Override
    public void run() {
        findViewById(R.id.fast_scrollView).scrollTo(xBefore, yBefore);
    }
};

@Override
public void afterTextChanged(Editable s) {
    Handler handler = new Handler();
    handler.postDelayed(myRunnable, 10);
}