scrollTo after focus/onClick event works only after second click

若如初见. 提交于 2019-12-08 12:17:23

问题


I try to scroll to specific point when the user click on edittext, so added the following code to listen to click and focus on this edittext:

    et_email = (EditText) view.findViewById(R.id.editEmail);
    //bring to center of screen when clicked / focused
    et_email.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ScrollView scrollView = (ScrollView)getView().findViewById(R.id.ScrollViewSendDetails);
            scrollView.smoothScrollTo(0, 500);
        }
    });
    et_email.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            ScrollView scrollView = (ScrollView) getView().findViewById(R.id.ScrollViewSendDetails);
            scrollView.smoothScrollTo(0, 500);
        }
    });

The problem is that the scrolling works only after the second click. In the first click on the edittext nothing happens


回答1:


Why do you have to listener for the same? Try to use an onTouch listener:

et_email.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (MotionEvent.ACTION_DOWN == event.getAction()) {
                ScrollView scrollView = (ScrollView)getView().findViewById(R.id.ScrollViewSendDetails);
                scrollView.smoothScrollTo(0, 500);
            }
            return false;
        }
    });



回答2:


Maybe a bit late but whoever is interested in a solution: replacing

scrollView.smoothScrollTo(0, 500)

with

scrollView.postDelayed(() -> scrollView.smoothScrollTo(0, 500), 200);

worked for me.



来源:https://stackoverflow.com/questions/34290504/scrollto-after-focus-onclick-event-works-only-after-second-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!