简体   繁体   中英

Remove focus from AutoCompleteTextView if swiped to another Fragment in the ViewPager

I have an issue with AutoCompleteTextView inside ViewPager fragment. AutoCompleteTextView data is loaded dynamically and it works fine, but if you swipe to another fragment (another page in ViewPager) fast enough, so before data is loaded then you get AutoCompleteTextView dropdown shown in the Fragment that you swiped to in meanwhile. In my example I have 3 fragments in the ViewPager, where the third contains AutoCompleteTextView, and if you swipe fast to the second sometimes you get dropdown on the second page, while it works fine if you swipe to the first since in that case third fragment is deallocated (setOffscreenPageLimit is 1 by default, so you always have one fragment in the memory for better UX). Has anyone run into the same problem?

I figured out a solution for my case, not sure if it would work ok for those who have AutoCompleteTextView or EditText on other ViewPager fragments. But anyway I did it like this:

in the MainActivity that holds viewPager I added clearFocus:

mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            if (position == 0 || position == 1) {
                if (getCurrentFocus() != null) {
                    getCurrentFocus().clearFocus();
                }
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            if (state == ViewPager.SCROLL_STATE_IDLE) {
                hideKeyboard();
            }
        }
    });

and in the third fragment I added requestFocus on the AutoCompleteTextView that need to have focus when that page in opened:

mAutoCompleteTextView.requestFocus();

Hope it helps someone

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM