ボクココ

個人開発に関するテックブログ

Android の ScrollView で EditText のキーボード非表示にしつつトップに移動する

毎回 ScrollView 付きのフォームを作るときに苦戦するのでメモ。

例えば、保存ボタンがScrollViewの一番下にあり、それを押すと検証が走る。 検証が失敗した時は一番上にエラーメッセージを出したいといった場合。

問題は、途中にあるEditTextのキーボードを非表示にしつつ、フォーカスを外して一番上まで持って行かなければならないという点。途中のフォーカスにひっかかって一番上までいってくれなくて、ハマる。。

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scrollView"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical"
        android:padding="@dimen/blank_medium"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/account_err_txt"
            android:visibility="invisible"
            android:focusable="true"
            android:focusableInTouchMode="true"
            style="@style/FormParts"
            android:text="Error Messages"
            android:textColor="@color/error" />

....

        <Button
            .....

    </LinearLayout>
</ScrollView>

ここで大事なのが、一番上にあるエラーメッセージのTextViewにフォーカスを当てられるようにすることだ。んでコードを書く。

findViewById(R.id.btn).setOnclickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
         // キーボードを隠す
         InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
         inputMethodManager.hideSoftInputFromWindow(ed.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);   

        // フォーカスを一番上にあるエラーテキストにセット
        errorText.requestFocus();
        // スクロールを一番上へ
        scrollView.fullScroll(View.FOCUS_UP);
    }
}

もっといい方法あるのかな。